Theory
Multiple returns & the copy trap
Two features you will need constantly.
Multiple returns. A Go function can return several values at once — usually a result plus a "did it work" flag:
func pagesPerDay(pages int, days int) (int, bool) {
if days == 0 {
return 0, false // cannot divide by zero
}
return pages / days, true
}
perDay, ok := pagesPerDay(380, 10)
if ok {
fmt.Println("Per day:", perDay)
}
You will meet this (value, ok) pair everywhere — in lesson 10 it becomes (value, error).
The copy trap. Go always passes a copy (pass by value). A function receives a duplicate of the argument, not the original:
func markRead(read bool) {
read = true // changes only the local COPY
}
read := false
markRead(read)
fmt.Println(read) // false — the original never changed!
Gotcha. The most common beginner mistake with functions: the function "changes" the value, yet the caller's variable stays as it was — because you changed a copy. For now the rule is simple: if a function must change something, have it return the new value. The real tool for changing the original — pointers — waits for you in lesson 11.