Understand the contract
An if condition in Go must be a boolean expression. Integers, strings and pointers are not implicitly converted to true or false. Compare a count with zero, a string with the empty string or a pointer with nil. Use an early return when invalid input makes the remaining work unnecessary.
A switch selects a matching case without automatically falling into the next case. The example uses an expressionless switch, so each case is a boolean condition. Conditions are evaluated in order and the first matching case runs. Keep more specific conditions ahead of broader ones.
Work through the example
The classify function rejects negative scores before assigning a category. With score 85, the second switch case returns "pass". Because every path returns a string, callers receive one result for every possible int. The braces around each control structure are required even for one statement.
package main
import "fmt"
func classify(score int) string {
if score < 0 { return "invalid" }
switch {
case score >= 90:
return "excellent"
case score >= 60:
return "pass"
default:
return "retry"
}
}
func main() { fmt.Println(classify(85)) }Watch this boundary
An initializer such as if n, err := strconv.Atoi(text); err != nil gives n and err a scope limited to the if and its else branches. Do not expect to use n afterward. Also avoid fallthrough unless the intended execution of the following case is explicit and necessary.
Practice with a changed input
Add a maximum valid score of 100. Check -1, 0, 59, 60, 89, 90 and 101 so that boundary behavior matches the categories you intended.
Lesson 10 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services