Structures
About
Go isn't a object-oriented language like Java or C#. It doesn't have objects, inheritance, polymorphism nor overloading.
What it does have are structures, which can be associated with methods.
Functions on Structures
In the above code, we say that the type *Foobar
is the receiver of the Baz
method.
Constructors
Go doesn't have a constructor method like other programming languages like Java do.
Instead, we create a function that returns an instance of the type.
Our function doesn't need to return a pointer. Below is also valid.
Go has a build-in new
function which is used to allocate the memory required by a type.
The result of new(X)
is the same as &X{}
:
But the latter is often preferred because we can specify fields to initialize in a more readable way.
Composition
Go supports composition: the act of including one structure into another.
This is called a trait or a mixin in some languages.
For example, Java doesn't have an explicit composition mechanism, so a mixin would be written like this:
This can be tedious because every method of Person
needs to be duplicated in Saiyan
.
Go avoids tediousness.
Overloading
Go doesn't support overloading. You'll see and write a lot of functions like Load
, LoadById
, LoadByName
and so on.
However, because implicit composition is really just a compiler trick, we can "overwrite" the functions of a composed type.
For example, our Saiyan
structure can have its own Introduct
function.
The composed version is always available via s.Person.Introduce()
.
REF
Many examples here are excerpted from The Little Go Book.
Last updated