Line At A Time
Lesson 25: Roll a Six
Roll a Six Grand finale: keep rolling a dice until you get a 6.
1package main
2
3import (
4 "fmt"
5 "math/rand"
6)
7
8func rollDice() int {
9 return rand.Intn(6) + 1
10}
11
12func main() {
13 roll := rollDice()
14 for roll != 6 {
15 fmt.Println(roll)
16 roll = rollDice()
17 }
18 fmt.Println("You rolled a 6!")
19}
Terminal
$ go run main.go
(prints a random number, different every run)
Every line, explained
package main
Every Go file starts by saying which package it belongs to. package main means "this is a program you can run", and Go will look inside it for func main.
import (
To import more than one package, Go uses this bracketed list, one package per line.
"fmt"
Our printing tools, as always.
"math/rand"
math/rand is Go's random-number package.
)
This ) closes the import list.
func rollDice() int {
func defines a function: a named block of code. Functions live at the top level of the file, next to main (never inside it). Go doesn't care about their order, but putting helpers first reads nicely top-to-bottom. This one promises to hand back an int: a dice roll.
return rand.Intn(6) + 1
rand.Intn(6) gives a random whole number from 0 to 5 (Intn stops just below the number you give it), so + 1 turns it into a proper dice roll from 1 to 6.
}
This } closes the function.
func main() {
func main() { ... } is where a Go program starts. When you run the program, Go finds func main inside package main and runs everything between its braces, top to bottom.
roll := rollDice()
Calls rollDice and stores the number it returns: our first roll.
for roll != 6 {
Go has exactly ONE loop keyword: for. Write it with just a condition and it behaves like other languages' while, repeating as long as the condition is true. != means "not equal": keep looping while the roll is NOT a 6.
fmt.Println(roll)
fmt.Println(...) prints what is inside the brackets to the terminal, then moves to a new line (Println is short for "print line"). The capital P matters: in Go, the tools a package shares all start with a capital letter. Shows each roll that wasn't a 6.
roll = rollDice()
Rolls again, replacing the old number (plain =, because roll already exists). Then the loop checks again.
}
This } closes the for loop.
fmt.Println("You rolled a 6!")
fmt.Println(...) prints what is inside the brackets to the terminal, then moves to a new line (Println is short for "print line"). The capital P matters: in Go, the tools a package shares all start with a capital letter. Runs once, the moment a 6 finally appears. You just used the scaffold, :=, a function with a return value, a loop and randomness. Real Go!
}
This closing brace } ends func main.