What Is a Struct?
Bundle related data into one value.
1package main
2
3import "fmt"
4
5type Dog struct {
6 name string
7}
8
9func main() {
10 rex := Dog{name: "Rex"}
11 fmt.Println(rex.name)
12}
$ go run main.go
Rex
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- A field: every Dog has a name, and it is a string. Go style: the name first, then the type.
}- This } closes the struct definition.
func main() {- func main() { ... } is where the program starts.
rex := Dog{name: "Rex"}- This builds an actual Dog value from the blueprint, filling in its name field right away. The field values go between curly braces, each written as field: value.
fmt.Println(rex.name)- fmt.Println(...) prints to the terminal, exactly as in Intro to Go. The dot reaches inside: rex.name is the name field of the dog stored in rex.
}- This } closes func main.