Member-only story
Writing a Ternary Operator in Go
How to build a custom ternary operator in Go by using generics
With the introduction of generics, many common utilities available in other languages are now implementable also in Go.
Probably one of the most important examples is the slices package, with functions such as search, min, or max useful for slices of any kind.
In this article we will look at one of the possible ways of using generics to develop a custom ternary operator in Go.
Ternary operator in common languages
One of my favorite applications of generics is the creation of a custom ternary operator, like those available in other languages such as Javascript or Python.
The idea is to set a variable in one line, based on a given condition and two possible values for the true and false case.
In Go to do such a thing might require at least four lines: one for the assignment and three more for the if case, making this approach more verbose.
https://go.dev/play/p/3643A_wZljd
n := 1
msg := "Even"
if n % 2 == 0 {
msg = "Odd"
}
fmt.Println(msg) // "Odd"
Without a way to write an if in one line, having multiple conditions like this in Go…