Coding for All
Lesson 5: Methods That Answer Back
Methods That Answer Back A method that returns a value.
1package main
2
3import "fmt"
4
5type Dog struct {
6 name string
7}
8
9func (d Dog) greeting() string {
10 return d.name + " says hi!"
11}
12
13func main() {
14 rex := Dog{name: "Rex"}
15 fmt.Println(rex.greeting())
16}
Terminal
$ go run main.go
Rex says hi!
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) greeting() string {
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". The string after the brackets is the return type: this method hands back text instead of printing it.
return d.name + " says hi!"
Builds the greeting from this dog's own name and returns it, just like the functions in Intro to Go, but attached to a Dog.
}
This } closes the function.
func main() {
func main() { ... } is where the program starts.
rex := Dog{name: "Rex"}
Build a dog.
fmt.Println(rex.greeting())
rex.greeting() becomes the returned text, and Println prints it.
}
This } closes func main.