One struct describes one session; a log needs many. Everything you learned about slices on Day 3 still applies when the items are structs. A slice of structs keeps records in the order you add them. Each pass of a range loop gets a copy of the record, so changing the loop variable leaves the slice alone. To change a record stored in the slice, use its index.
The type is written []Session. Inside the slice literal you can leave out the type name before each record, so []Session{{Title: "Poems", Minutes: 10}} is a slice holding one session. The outer braces belong to the slice and the inner braces to the record.
Predict and run
Which loop changes the record stored in the slice?
package main
import (
"fmt"
)
type Session struct {
Title string
Minutes int
}
func main() {
sessions := []Session{{Title: "Poems", Minutes: 10}}
for _, session := range sessions {
session.Minutes = 20
}
fmt.Println(sessions[0].Minutes)
for i := range sessions {
sessions[i].Minutes = 20
}
fmt.Println(sessions[0].Minutes)
}Check your prediction
10
20Add a second session to the slice and print sessions[1].Minutes at the end. Predict it first.
Reading records with range
Most of the time you only read records, and the copy that range gives you is exactly what you need. Write one record per line in the slice literal, each followed by a comma, including the last one. Go requires that final comma when the closing brace is on its own line, and it means adding a record later touches only one line.
package main
import (
"fmt"
)
type Session struct {
Title string
Minutes int
}
func main() {
sessions := []Session{
{Title: "Poems", Minutes: 25},
{Title: "Short stories", Minutes: 35},
{Title: "Essays", Minutes: 15},
}
total := 0
for _, s := range sessions {
fmt.Printf("%-14s%3d min\n", s.Title, s.Minutes)
total += s.Minutes
}
fmt.Printf("%d sessions, %d min\n", len(sessions), total)
}Poems 25 min
Short stories 35 min
Essays 15 min
3 sessions, 75 minThe loop variable is named s here. Short names are normal in Go when the loop is short and the type makes the meaning clear.
Adding records
append works with structs exactly as it does with numbers. Build the new record in the call, or build it first in a variable and append the variable. Either way, store the result back into the slice.
package main
import (
"fmt"
)
type Session struct {
Title string
Minutes int
}
func main() {
var log []Session
log = append(log, Session{Title: "Poems", Minutes: 10})
next := Session{Title: "Essays", Minutes: 20}
log = append(log, next)
next.Minutes = 99
fmt.Println(len(log), log[1].Minutes)
}2 20Changing next after appending it does not touch the log: append stored a copy of the record, not a link to the variable.
Copies are the default
Assignments, function arguments, range variables and append all copy a struct. That makes records predictable, because nothing changes behind your back. The flip side is that an update meant for the slice must go through the slice itself, as in sessions[i].Minutes = 20.
Choosing between the two loops
Use for _, s := range sessions when you read records, such as for a report or a total. Use for i := range sessions when you change them, and refer to each record as sessions[i]. Picking the loop by what you intend to do makes the copy rule work for you instead of against you.
Practice
Your turn
The starter holds three sessions and prints them. The Essays session was really 5 minutes longer. Change the record stored in the slice, then print the whole log again under an After heading. The output should be:
Before
Poems 10
Essays 20
Plays 15
After
Poems 10
Essays 25
Plays 15package main
import (
"fmt"
)
type Session struct {
Title string
Minutes int
}
func main() {
sessions := []Session{
{Title: "Poems", Minutes: 10},
{Title: "Essays", Minutes: 20},
{Title: "Plays", Minutes: 15},
}
fmt.Println("Before")
for _, s := range sessions {
fmt.Println(s.Title, s.Minutes)
}
}Hint 1: the idea
A change has to reach the record inside the slice, not a copy of it. That means going through the slice with an index.
Hint 2: a first step
Essays is the second record, so its index is 1. Try s := sessions[1] followed by s.Minutes += 5 first, and see that the log doesn't change. Then work out why.
Worked solution
package main
import (
"fmt"
)
type Session struct {
Title string
Minutes int
}
func main() {
sessions := []Session{
{Title: "Poems", Minutes: 10},
{Title: "Essays", Minutes: 20},
{Title: "Plays", Minutes: 15},
}
fmt.Println("Before")
for _, s := range sessions {
fmt.Println(s.Title, s.Minutes)
}
sessions[1].Minutes += 5
fmt.Println("After")
for _, s := range sessions {
fmt.Println(s.Title, s.Minutes)
}
}Before
Poems 10
Essays 20
Plays 15
After
Poems 10
Essays 25
Plays 15sessions[1].Minutes += 5 names the field of the record stored in the slice. s := sessions[1] copies the record, so changing s leaves the slice alone. That is the same copy rule range follows. Both print loops only read, so they keep the shorter _, s form.
Completion is saved in this browser only. It does not measure mastery.