Coding for All
Lesson 4: Methods
Methods Attach a method to your struct.
1package main
2
3import "fmt"
4
5type Dog struct {
6 name string
7}
8
9func (d Dog) bark() {
10 fmt.Println(d.name, "says woof!")
11}
12
13func main() {
14 rex := Dog{name: "Rex"}
15 rex.bark()
16}
Terminal
$ go run main.go
Rex says woof!
Every line, explained
package main
Every Go file starts by saying which package it belongs to, exactly as in Intro to Go.
import "fmt"
import "fmt" brings in the printing tools, as always.
type Dog struct {
type Dog struct { ... } defines a struct: a bundle of fields that belong together. Go has no classes; structs are how Go groups data, and they do the job beautifully.
name string
Every Dog has a name.
}
This } closes the struct definition.
func (d Dog) bark() {
The (d Dog) before the name is the receiver: it is what attaches this function to Dog values, turning it into a method. Inside, d is "the dog this method was called on". This is how Go writes what other languages call a class method.
fmt.Println(d.name, "says woof!")
d.name is the name of whichever dog is barking: when rex barks, d is rex.
}
This } closes the function.
func main() {
func main() { ... } is where the program starts.
rex := Dog{name: "Rex"}
Build a dog.
rex.bark()
The dot calls the method: rex.bark() means "rex, bark!", and the method prints rex's own name.
}
This } closes func main.