Two Dogs
Build two independent values from one struct.
1package main
2
3import "fmt"
4
5type Dog struct {
6 name string
7}
8
9func main() {
10 rex := Dog{name: "Rex"}
11 bella := Dog{name: "Bella"}
12 fmt.Println(rex.name)
13 fmt.Println(bella.name)
14}
$ go run main.go
Rex
Bella
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- The blueprint says every Dog has a name.
}- This } closes the struct definition.
func main() {- func main() { ... } is where the program starts.
rex := Dog{name: "Rex"}- One struct definition...
bella := Dog{name: "Bella"}- ...as many values as you like. Think of one house plan and a whole street of houses. bella's name field is completely separate from rex's.
fmt.Println(rex.name)- fmt.Println(...) prints to the terminal, exactly as in Intro to Go.
fmt.Println(bella.name)- fmt.Println(...) prints to the terminal, exactly as in Intro to Go. Two values, two different names.
}- This } closes func main.