go · level 1 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Big programs are small pieces working as a team.
A bundles values into one, like a pet's record card. type Pet struct lists its fields, each with a name and a type. Make a card with Pet{Name: "Rex", Age: 3}, and read a with a dot: pet.Name.
Real programs are built from small parts. A slice of structs holds the data, a loop walks through it, a function answers one question and an if decides what to do.
When something goes wrong, you : find the bug, fix it, run again. Every programmer does this every day. Small functions help, because you can test each one on its own.
package main
import "fmt"
type Pet struct {
Name string
Age int
}
func main() {
pets := []Pet{{Name: "Rex", Age: 3}, {Name: "Tibbles", Age: 12}}
for _, pet := range pets {
fmt.Printf("%v is %v\n", pet.Name, pet.Age)
}
} Inside a slice of Pet, you can leave out the word Pet before each card's curly brackets.
guess first
Prices have doubled. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
type Snack struct {
Name string
Price int
}
func main() {
snack := Snack{Name: "crisps", Price: 2}
snack.Price = snack.Price * 2
fmt.Println(snack)
}
your turn
Your turn. Fill in a pet's record card.
Make a record card for a pet, real or made up. Type its name between the quotes and its age as a whole number. The describe function does the rest.
output
press run to see what happens
fix it
The wise old cat cannot be found. Debug it!
output
press run to see what happens
- Read the error on line 9. Which field does Go say it cannot find?
- Go is case-sensitive. The struct's field is called Age, with a capital A.
- Change pet.age to pet.Age on line 9, then run.
nailed it
you put all the pieces together. :D
- A struct bundles named fields, like a record card.
- Read a field with a dot, like
pet.Name. - To debug, find the bug, fix it, then run again.
new words in your collection
- struct
- field
- debug
This lesson isn’t saved. A free account remembers every lesson you finish.