Why do we have the methods declared outside the type definition of the struct? E.g.:
type antenna struct {
name string
length float32
girth float32
bloodtype string
}
func (p *antenna) extend() {
p.length += 10
}
It seems to me that the method could be part of the struct? (Let's ignore for now that structs are supposed to be value types)
type antenna struct {
name string
length float32
girth float32
bloodtype string
func extend() {
length += 10
}
}
This would be more similar to traditional OOP. I didn't find any good explanations of why it is done the way it is besides "structs are value-types and classes are reference-types". I know the difference, but it's not a satisfactory answer to me. In any way the method has to be called like this:
var x = antenna()
x.extend()
So what's the point of separating the the struct and methods? Having them visually grouped together in the code - as in typical OOP languages - seems useful to me?
My Viewpoints:
1. It is simpler this way and makes language consistent/uniform for struct types and other types like following code.
2. You don't need this
or self
pointer to use and you name it as you wish, and this makes it even simpler to explain what is p
(in your example).
Also may be this is relevant:
In Go is naming the receiver variable 'self' misleading or good practice?
You may define your own types, See this sample (There is no inside or struct here for this named type):
package main
import "fmt"
type num int32
func (p *num) inc() {
*p++
}
func main() {
p := num(100)
p.inc()
fmt.Println(p) // 101
}
In golang, if we need a function associated with a type (say struct
), then it must be defined as below (here is for go struct
):
type my_type struct {
// fields ...
}
func (m my_type) fn_name(fn_parameters) fn_return_type {
// do whatever we want
}
It's not something you define in your own way. But the identifier's names can be used as we want.