In most languages a function that fails throws an exception, and the failure silently travels up until something (maybe) catches it. Go takes a different route: errors are ordinary values that functions hand back to you, right next to the result. That works because a Go function can return more than one value.
The classic example is strconv.Atoi, which converts a string to an int. Its signature says it returns TWO things:
func Atoi(s string) (int, error)
So you call it with two names on the left, and then look at err:
value, err := strconv.Atoi("42")
if err != nil {
fmt.Println("error:", err) // something went wrong — err explains what
} else {
fmt.Println("value =", value) // err is nil — safe to use the number
}
nil means "no error, it worked". Anything else is a description of the failure.
The trap: you cannot ignore the error
Try to grab just the number and the compiler stops you cold:
value := strconv.Atoi("42") // take one value... nope
./main.go:9:14: assignment mismatch: 1 variable but strconv.Atoi returns 2 values
Take err but never look at it? Also a compile error:
./main.go:9:12: err declared and not used
The only escape hatch is the blank identifier _ — and that's exactly where bugs hide. value, _ := strconv.Atoi("42x") compiles, but value is silently 0 and you'll never know the parse failed. In real Go code you'll constantly see the early-return idiom instead:
if err != nil {
return err // stop here, pass the problem to the caller
}
Assignment
Follow the Coding Tutorial and walk both paths of the same call:
- parse
"42"withvalue, err := strconv.Atoi("42"), checkerr != nil, and print the error orvalue =with the number, - then parse
"42x"into the same variables (plain=) and run the exact same check — this time the error branch fires.
The exact expected output is:
value = 42
error: strconv.Atoi: parsing "42x": invalid syntax
Hint
The second call reuses value and err, so it needs plain assignment =, not := — Go refuses to re-declare variables that already exist.
Free plan: 30 tutor messages. PRO is unlimited.
