Go — Choosing a value with a guarded return
Go uses an if statement or a helper with early returns to select between two results. This is the idiomatic equivalent of a ternary expression.
A simple example
Choose one value
- Start with n is 2
- Do this Choose by sign
- Result positive
package main
import "fmt"
func sign(n int) string {
if n > 0 {
return "positive"
}
return "other"
}
func main() {
fmt.Println(sign(2))
}
positive
Choose a report value when a sample is missing
Report a whole-number average for a nonempty group and a text label for an empty group. Guard the division where the result is selected. Return the empty-group label before the division. All remaining paths can then assume a positive sample count under the example's nonnegative-count contract.
A monitor displays the average of a sensor’s samples. If no sample arrived, show a message before attempting division. Three samples with a total of 18 give an average of 6.
Run the example
Use Go 1.21 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
"strconv"
)
func meanLabel(total, count int) string {
if count == 0 {
return "no samples"
}
return strconv.Itoa(total / count)
}
func main() {
for _, count := range []int{0, 3} {
fmt.Println(meanLabel(18, count))
}
}
no samples 6
The first group has zero samples and displays no samples. In the second group, 18 divided by 3 gives 6.
Try it yourself
What does an observed total of zero with three samples display?
Check your answer
It displays 0. This is a measured zero, whereas the empty group has no average.