A Go method is a function with a receiver: a value of the type the method belongs to. Use one when behavior needs access to a value’s fields without passing those fields as separate arguments. Unlike a function stored in a struct field, a method can use its receiver to reach the struct’s data. section 3.1.2
Read with a value receiver; change with a pointer receiver
This complete program uses a value receiver to choose a sound from the animal’s name. The pointer receiver changes that name for the next call. package main import "fmt" type Animal struct { name string } func (a Animal) speak() string { switch a.name { case "cat": return "meow" case "dog": return "woof" default: return "nondescript animal noise?" } } func (a *Animal) rename(name string) { a.name = name } func main() { a := Animal{name: "cat"} fmt.Println(a.speak()) a.rename("dog") fmt.Println(a.speak()) } section 3.1.2
Listing 3.3 A pointer receiver method
package main
import (
"fmt"
)
type character struct {
name string
}
func (ch *character) fixName() {
ch.name = "Inigo Montoya"
}
func main() {
ch := new(character) #1
ch.name = "Prince Humperdinck"
fmt.Println("my name is", ch.name)
ch.fixName() #2
fmt.Println("just kidding, my name is", ch.name) #3
}
A focused pointer-receiver example shows a method changing a struct field and the caller observing the new value. section 3.1.2
Methods also connect types to interfaces. An interface can require a method such as speak(); a struct without it cannot be assigned to that interface. This provides an alternative to relying on a superclass for shared behavior: each participating Go type supplies the required method. section 3.2
Listing 3.6 The same idea in Go
package main
import (
"fmt"
)
type Animal interface { #1
speak()
}
type Cat struct {} #2
func (c Cat) speak() {
fmt.Println("meow") #3
}
func NewCat() *Cat { #4
return &Cat{}
}
type Dog struct {}
func (d Dog) speak() {
fmt.Println("woof")
}
func NewDog() *Dog {
return &Dog{}
}
type Llama struct {}
func NewLlama() *Llama { #5
return &Llama{}
}
func main () {
var a Animal
c := NewCat()
a = c
a.speak()
d := NewDog()
a = d
a.speak()
l := NewLlama()
a = l
}
Compare the types that implement speak() with the one that does not. Assigning the latter to the interface produces the missing-method error. section 3.2



















