Line At A Time
Lesson 19: Adding It Up
Adding It Up Total up all the numbers in a slice.
1package main
2
3import "fmt"
4
5func main() {
6 prices := []int{2, 4, 6}
7 total := 0
8 for _, price := range prices {
9 total += price
10 }
11 fmt.Println(total)
12}
Terminal
$ go run main.go
12
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 "fmt"
import brings in a package from Go's standard library. "fmt" (short for format) is the one full of printing tools, like fmt.Println.
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.
prices := []int{2, 4, 6}
A slice is Go's list. []string means "a slice of strings", and the items go between curly braces. Every item must be the same type. This one is a []int, a slice of whole numbers.
total := 0
:= is Go's declare-and-assign: it creates a new variable AND stores a value in one step, and Go works out the type by itself. You will use := constantly in Go. (No semicolon needed; Go adds them for you behind the scenes.) total starts at 0 and will collect the running sum.
for _, price := range prices {
for ... range visits each item of a slice. range offers TWO things each trip: the position and the item. We only want the item, so we put _ (the "blank identifier", Go's way of saying "ignore this") where the position would go.
total += price
+= adds the value on the right onto the variable on the left: 0+2=2, 2+4=6, 6+6=12. A shorter way of writing total = total + price.
}
This } closes the for loop.
fmt.Println(total)
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. After the loop finishes, total is 12.
}
This closing brace } ends func main.