Code
Refactor main.go — three variables become one record
Three loose variables become one record. Add the struct at the top, then thread it through the two functions.
Add the type above main:
// Item is one record of the list — the fields that used to travel around
// as three loose variables.
type Item struct {
Title string
Pages int
Read bool
}
In main, replace the three variable lines with one literal:
it := Item{Title: "The Go Programming Language", Pages: 380, Read: false}
Then update the two functions to take an Item and reach its fields with a dot:
func formatItem(it Item) string {
return fmt.Sprintf("Book: %s | pages: %d | read: %v", it.Title, it.Pages, it.Read)
}
func printItem(it Item) {
fmt.Println(formatItem(it))
}
Item{...} is a literal: it creates a record and fills the fields by name. Inside the functions, it.Title reaches a field with a dot. One value now carries what used to be three.
Verify — for the third time in a row, the same output:
App: Book list
Book: The Go Programming Language | pages: 380 | read: false
Tip. Three lessons, three refactors, zero behavior changes — the shape changes, the behavior is protected. From the next lesson the behavior finally changes too: the program becomes interactive.