Often, when you want to simulate an object-oriented style, where you have an “object” that stores state and “methods” that can modify the object, then you will have a “constructor” function that returns a pointer to (think about it as an "object reference", as in other OO languages). Mutator methods would have to be pointer-to-structure methods instead of the structure type itself in order to change the fields of the object, so it’s convenient to have a pointer to the structure instead of the structure of the value itself, so that all the methods will be installed in its method.
For example, to reproduce something like this in Java:
class Car { String make; String model; public Car(String myMake) { make = myMake; } public setMake(String newMake) { make = myMake; } }
In Go, you'll often see something like this:
type Car struct { make string model string } func NewCar(myMake string) *Car { return &Car{myMake, ""} } func (self *Car) setMake(newMake string) { self.make = newMake }
newacct
source share