Practice
Go exercises
Make a change, predict what it will do, and compare the result.
- 1
Go Basics
Print a message from main.
Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.
Show starting example
Gopackage main import "fmt" func main() { name := "Ada" fmt.Println("Hello,", name) } - 2
Go Functions and Multiple Return Values
Return more than one value from a function.
Predict divide(20, 6).
Reveal answer and reasoning
It returns 3 and 2, so the output is 3 2.
Show starting example
Gopackage main import "fmt" func divide(a, b int) (int, int) { return a / b, a % b } func main() { q, r := divide(17, 5) fmt.Println(q, r) } - 3
Go Loops
Count with the for statement.
Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.
Show starting example
Gopackage main import "fmt" func main() { for i := 1; i <= 3; i++ { fmt.Println(i) } } - 4
Go Structs and Methods
Group fields in a struct and attach behavior to it.
Add a Perimeter method.
Reveal answer and reasoning
func (r Rect) Perimeter() int { return 2 * (r.Width + r.Height) } returns 14 for this rectangle.
Show starting example
Gopackage main import "fmt" type Rect struct { Width, Height int } func (r Rect) Area() int { return r.Width * r.Height } func main() { r := Rect{Width: 3, Height: 4} fmt.Println(r.Area()) } - 5
Go Slices
Grow a sequence with append and take a part of it.
What does scores[:2] print for the final slice?
Reveal answer and reasoning
It runs from the start up to index 2, so it prints [82 91].
Show starting example
Gopackage main import "fmt" func main() { scores := []int{82, 91, 76} scores = append(scores, 95) fmt.Println(len(scores), scores[3]) fmt.Println(scores[1:3]) }