Go Structs and Methods
ExampleGo
package main
import "fmt"
type Person struct {
Name string
Age int
}
func (p Person) Describe() string {
return fmt.Sprintf("%s is %d", p.Name, p.Age)
}
func (p *Person) Birthday() {
p.Age++
}
func main() {
p := Person{Name: "Ada", Age: 36}
p.Birthday()
fmt.Println(p.Describe())
fmt.Printf("%+v\n", p)
}Output
Ada is 37
{Name:Ada Age:37}A method is a function attached to a type. A pointer receiver (*Person) lets the method change the original value.
Quick check
Why does Birthday use a *Person receiver?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.