Max of a slice in Go
Finds the largest element, and shows why an empty slice needs a decision.
func max(items []int) (int, error) {
if len(items) == 0 {
return 0, errors.New("empty slice")
}
best := items[0]
for _, v := range items[1:] {
if v > best {
best = v
}
}
return best, nil
}
Keywords and builtins used here
errorforfuncifintlenmaxrangereturn
The run, in numbers
- Lines
- 12
- Characters to type
- 188
- Tokens
- 65
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 43 seconds.
Step 6 of 9 in Arrays, slices & maps, step 21 of 30 in Language basics.