Skip to content

Instantly share code, notes, and snippets.

@davidlares
Last active July 13, 2021 06:49
Show Gist options
  • Save davidlares/e9806db9b91598a756d042f7d1a3dd33 to your computer and use it in GitHub Desktop.
Save davidlares/e9806db9b91598a756d042f7d1a3dd33 to your computer and use it in GitHub Desktop.
The 'OOP' perspective in Golang

The OOP perspective in Golang

At a certain moment, when working with Golang we mentally start thinking about classes and methods, just the regular OOP way of working.

In the OOP approach, a Struct data type can be seen as a Class definition, the Blueprint for incoming objects, where, variables or even arrays can be seen as attributes and some functions can be seen as methods.

But that's not all correct.

The ideal scenario here is that we need a way to extending a base type to add some extra functionality. By base types, I'm referring to strings, integers, arrays, maps, and so on. Any custom method that can be appliable to an instance, we can 'associate' it to an OOP object.

This can be achieved by the use of Receivers, this is like an object function that expects a certain type of element to invoke it.

You can understand this better with an example.

func (c car) startEngine() {
 ....
}

Here:

  1. The c is the actual copy of the car "instance" we are working with
  2. The car references the working variable
  3. The startEngine() is the function itself.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment