Learn Struct in Go

type Menu struct { Name string; Price int } makes a type with named fields. A value is made with a struct literal Menu{Name: "Tendon Meatballs", Price: 15}…

One dish at Bimo's Meatball Stall has several details at once: name, price, and spicy or not. If every detail sits in its own variable, then by the time the menu has ten dishes, you have thirty variables that are easy to mix up.

A struct groups those related values into one, each with its own name and type. Think of a menu card: every card has the same columns, the struct is the card template, and each dish is one card filled in. It's like an object in JavaScript, except the columns are set in advance through a type, and you can't just add more.

Defining a struct

type Menu struct {
	Name  string
	Price int
	Spicy bool
}

Making a struct value

meatballs := Menu{Name: "Tendon Meatballs", Price: 15, Spicy: true}
tea := Menu{Name: "Iced Tea", Price: 5}
var empty Menu

fmt.Println(meatballs) // {Tendon Meatballs 15 true}
fmt.Println(tea)       // {Iced Tea 5 false}
fmt.Println(empty)     // { 0 false}

Read, change and print fields

fmt.Println(meatballs.Name, meatballs.Price) // Tendon Meatballs 15

fmt.Printf("%v\n", meatballs)  // {Tendon Meatballs 15 true}
fmt.Printf("%+v\n", meatballs) // {Name:Tendon Meatballs Price:15 Spicy:true}
fmt.Printf("%#v\n", meatballs) // main.Menu{Name:"Tendon Meatballs", Price:15, Spicy:true}

meatballs.Price = 16
fmt.Println(meatballs.Price) // 16

A struct is a value: copied whole

meatballs := Menu{Name: "Tendon Meatballs", Price: 15, Spicy: true}
copied := meatballs
copied.Price = 18
fmt.Println(meatballs.Price, copied.Price) // 15 18

copied := meatballs copies every field into a new struct, just like an array and unlike a slice. So meatballs.Price stays 15.

A struct as a function parameter

func printMenu(m Menu) {
	fmt.Printf("\"%s\": $%d\n", m.Name, m.Price)
}

func raisePrice(m Menu) {
	m.Price = 20 // only changes this function's own copy
}
printMenu(meatballs)         // "Tendon Meatballs": $15
printMenu(tea)               // "Iced Tea": $5
raisePrice(meatballs)
fmt.Println(meatballs.Price) // 15

A struct inside a struct, and anonymous structs

type Order struct {
	Menu     Menu
	Portions int
}

order := Order{Menu: tea, Portions: 2}
fmt.Printf("%+v\n", order)                                    // {Menu:{Name:Iced Tea Price:5 Spicy:false} Portions:2}
fmt.Println(order.Menu.Name, order.Portions*order.Menu.Price) // Iced Tea 10

guest := struct {
	Name  string
	Table int
}{Name: "Sari", Table: 3}
fmt.Printf("%+v\n", guest) // {Name:Sari Table:3}

💡 Field tags for JSON

type MenuJSON struct {
	Name  string `json:"name"`
	Price int    `json:"price"`
	Spicy bool   `json:"spicy,omitempty"`
	stock int
}

b, _ := json.Marshal(MenuJSON{Name: "Iced Tea", Price: 5, stock: 20})
fmt.Println(string(b)) // {"name":"Iced Tea","price":5}

⚠️ Copies, literals without field names, and fields missing from JSON

TL;DR: type Menu struct { Name string; Price int } makes a type with named fields. A value is made with a struct literal Menu{Name: "Tendon Meatballs", Price: 15}, fields you don't mention hold their zero value, and var m Menu is all zero values. m.Name reads and changes a field. %v prints the values, %+v with field names, %#v like Go code. A struct is a value: assigning and function parameters make a copy. An anonymous struct is a struct with no type name, and tags such as json:"name" are read by other packages.

⚡ A menu card template

Write:

type Menu struct {
	Name  string
	Price int
	Spicy bool
}

Meaning: type Menu struct makes a new type. Every line is a field: its name, then its type. Fields that start with a capital letter can be used from other packages.

⚡ A struct literal

Write:

meatballs := Menu{Name: "Tendon Meatballs", Price: 15, Spicy: true}
fmt.Println(meatballs.Name) // Tendon Meatballs

Meaning: The type name, then curly braces holding Field: value. A field you don't mention holds its zero value, and meatballs.Price = 16 changes one field.

⚡ A struct is copied whole

Guess first: copied := meatballs, then copied.Price = 18. What is meatballs.Price now?

Still 15. A struct is a value, so copied := meatballs copies every field. A function parameter gets a copy too.

Meaning: A struct is copied like an array, unlike a slice.

⚡ A struct with no type name

Write:

guest := struct {
	Name  string
	Table int
}{Name: "Sari", Table: 3}

Meaning: This is an anonymous struct: a struct defined and used on the spot without a type name. Handy for one-off data. When the shape is used again and again, make a type.

What you will learn