type UserModel struct {
...
}
func (u *UserModel) C() string {
return "system_users"
}
The above will assign an embedded struct to the type UserModel
, does Go allow the same to be done with var
s or const
s?
Something like
var (u *UserModel) C = "system_users"
You get the idea.
Methods is a functions with receivers bound to a types. Receiver could take a value or a pointer to a type which method bound to.
Go by example provides this nice example:
type rect struct {
width, height int
}
// This `area` method has a _receiver type_ of `*rect`.
func (r *rect) area() int {
return r.width * r.height
}
// Methods can be defined for either pointer or value
// receiver types. Here's an example of a value receiver.
func (r rect) perim() int {
return 2*r.width + 2*r.height
}
And yes you can define methods on almost all existing types except interface
. Also it must be local type (defined in a package not built-in)
type Int int
func (i Int) Add(j Int) Int {
return i + j
}
Generalizing "Effective Go" a bit:
The methods of embedded types come along for free. Which means that if type B embedded to type A than type A not only has its own methods it also has methods of type B.
Extending previous example:
type parallelogram struct {
rect // Embedding. parallelogram has area and perim methods
depth int
}
func (p parallelogram) volume () int { // Extending rect
// Volume logic
}