Coding for All
Lesson 2: More Fields
More Fields Give the struct several fields.
1package main
2
3import "fmt"
4
5type Dog struct {
6 name string
7 age int
8}
9
10func main() {
11 rex := Dog{name: "Rex", age: 3}
12 fmt.Println(rex.name, "is", rex.age)
13}
Terminal
$ go run main.go
Rex is 3
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...
age int
...and an age. A struct can bundle as many fields as you need, of any types.
}
This } closes the struct definition.
func main() {
func main() { ... } is where the program starts.
rex := Dog{name: "Rex", age: 3}
Fills in both fields at once, separated by a comma.
fmt.Println(rex.name, "is", rex.age)
fmt.Println(...) prints to the terminal, exactly as in Intro to Go. Println with commas prints the pieces with spaces between them: Rex is 3.
}
This } closes func main.