Theory
Pseudocode → Go
Now the promised bridge. Keep step 1's pseudocode in mind on the left; on the right — real Go:
package main
import "fmt"
func main() {
numbers := []int{7, 42, 13, 8}
biggest := numbers[0] // start from the FIRST value, not from 0
for _, n := range numbers {
if n > biggest {
biggest = n
}
}
fmt.Println("Largest:", biggest)
}
Match the lines to the pseudocode:
- "Take the first number" →
biggest := numbers[0] - "Walk through the rest one by one" →
for _, n := range numbers - "If bigger — replace" →
if n > biggest { biggest = n } - "The answer" →
fmt.Println("Largest:", biggest)
The new constructs ([]int, range, if) are not today's topic — lessons 5 and 7 cover them properly. Today one thing matters: code is a translation of pseudocode, not magic.
Gotcha. Why
biggest := numbers[0]and notbiggest := 0? If the list is all negative numbers (say{-7, -3, -12}), starting from 0 would give the answer 0 — a number that is not in the list. Start from the first real element and the algorithm is correct every time.