💻 Tech
In Go, we refer to methods
as callable behaviors that are part of a struct. You’ll see it with a receiver before its name, just like (p Person) DisplayName()
. In contrast, functions
don’t have receivers. Under the hood, Go executes methods
as functions
. Bill Kennedy calls methods as syntactic sugar. You can see it in the code below.
The example code shows that you can actually call a method as function, which is not a normal coding style but it’s what Go does under the hood.
type Person struct {
Name string
Age int
}
func (p Person) DisplayName() {
fmt.Println(p.Name)
}
func (p *Person) SetAge(age int) {
p.Age = age
}
func main() {
p := Person{Name: "Joe"}
// How we normally call the method
p.DisplayName()
p.SetAge(12)
fmt.Println(p.Age)
// How Go is doing it; it's calling it as a function
Person.DisplayName(p)
(*Person).SetAge(&p, 21)
fmt.Println(p.Age)
}
Output:
Joe
12
Joe
21