Skip to content

Describe One Record

The Course
•
18 min study

A reading session has a title and a duration. Keeping them in two separate variables, or two separate slices, means every piece of code has to remember which title belongs to which number. A struct groups named fields, which can have different types. Declare the type once with type Session struct. Build a value with a literal that names each field, and read a field with a dot, as in session.Title.

Declaring type Session struct creates a new type, just like int or string but designed by you. The fields are listed between braces, one per line, each with a name and a type. Declare the type at the top level of the file, outside main, so every function in the file can use it.

Predict and run

Which field provides the printed number?

Predict, then run Go
package main

import (
	"fmt"
)

type Session struct {
	Title   string
	Minutes int
}

func main() {
	session := Session{Title: "Poems", Minutes: 25}
	fmt.Println(session.Title, session.Minutes)
}
Check your prediction
Text
Poems 25

Leave Minutes out of the literal and run it. A missing field gets its zero value: 0 for an int and "" for a string.

Building and changing a struct value

The literal Session{Title: "Poems", Minutes: 25} names each field, so the order you write them in does not matter and a reader can see which value goes where. You can also write the values without names, Session{"Poems", 25}, but then they must follow the declaration order exactly and every field must be present. The named form survives a new field being added to the type later, so prefer it.

A struct value is a variable like any other, so you can assign to a field with = or +=. var session Session declares a value with every field at its zero value, ready to be filled in.

Update fields Go
package main

import (
	"fmt"
)

type Session struct {
	Title   string
	Minutes int
}

func main() {
	var session Session
	session.Title = "Letters"
	session.Minutes += 20
	session.Minutes += 15
	fmt.Printf("%s: %d min\n", session.Title, session.Minutes)
	fmt.Printf("%+v\n", session)
}
Text
Letters: 35 min
{Title:Letters Minutes:35}

The %+v verb prints a struct with its field names, which is very useful while you are checking what a value holds.

Field names and capital letters

The convention in Go is to start type and field names with a capital letter, as in Session, Title and Minutes. A capital letter makes a name visible to other packages. Inside one main package it makes no difference yet, but the course uses capitals so the code is ready to be split into packages later.

Passing a struct to a function

A struct can be a parameter or a result, which lets a function work with a whole record instead of loose values. Like an int, a struct is copied when you pass it, so a function that changes its parameter's fields changes only its own copy. Return the changed struct if the caller needs it.

A function that reads a record Go
package main

import (
	"fmt"
)

type Session struct {
	Title   string
	Minutes int
}

func describe(s Session) string {
	return fmt.Sprintf("%s (%d min)", s.Title, s.Minutes)
}

func main() {
	poems := Session{Title: "Poems", Minutes: 25}
	fmt.Println(describe(poems))
}
Text
Poems (25 min)
Let the type carry the meaning

A function that takes a Session cannot be called with the title and the minutes swapped, because there is only one argument. Grouping values into a struct removes a whole class of mix-ups that two plain parameters would allow.

Practice

Exercise

Your turn

The starter declares Session. Write a function label that takes a Session and returns "Long" when it lasts 30 minutes or more, and "Short" otherwise. In main, create an Essays session of 35 minutes and print its title and label. Then change its minutes to 20 and print them again. The output should be:

Text
Essays Long
Essays Short
Your working space Go
package main

type Session struct {
	Title   string
	Minutes int
}

func main() {
	// Write your code here.
}
Hint 1: the idea

A struct is passed to a function like any other value, and the function reads its fields with a dot. Changing a field in main changes the record that the next call receives.

Hint 2: a first step

Write the signature func label(s Session) string and make it return "Short" for now. Create the session with Session{Title: "Essays", Minutes: 35} and print session.Title and label(session).

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

type Session struct {
	Title   string
	Minutes int
}

func label(s Session) string {
	if s.Minutes >= 30 {
		return "Long"
	}
	return "Short"
}

func main() {
	session := Session{Title: "Essays", Minutes: 35}
	fmt.Println(session.Title, label(session))
	session.Minutes = 20
	fmt.Println(session.Title, label(session))
}
Text
Essays Long
Essays Short

label receives a copy, so it can read the record but not change it. The update happens in main, on the variable itself. Once return "Long" runs, the function ends, so the second return needs no else.

Was this article helpful?

Your response is saved on this device.