Appendix. Solutions

 

This appendix provides our solutions for the end-of-lesson exercises and capstone projects. Please keep in mind that there is more than one solution for any problem.

Note

You can download these solutions and the rest of the source code from the Manning website at www.manning.com/books/get-programming-with-go or browse the source code online at github.com/nathany/get-programming-with-go.

Unit 0

Lesson 1

Experiment: playground.go
package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, Nathan")
    fmt.Println(" hola")
}

Unit 1

Lesson 2

Experiment: malacandra.go
package main

import "fmt"

func main() {
    const hoursPerDay = 24

    var days = 28
    var distance = 56000000 // km

    fmt.Println(distance/(days*hoursPerDay), "km/h")
}

Lesson 3

Experiment: guess.go
package main

import (
    "fmt"
    "math/rand"
)

func main() {
    var number = 42

    for {
        var n = rand.Intn(100) + 1
        if n < number {
            fmt.Printf("%v is too small.\n", n)
        } else if n > number {
            fmt.Printf("%v is too big.\n", n)
        } else {
            fmt.Printf("You got it! %v\n", n)
            break
        }
    }
}

Lesson 4

Unit 2

Unit 3

Unit 4

Unit 5

Unit 6

Unit 7