I'm used to C/Java, where I could use ?: as in:
func g(arg bool) int {
return mybool ? 3 : 45;
}
Since Go does not have a ternary operator, how do I do that in go?
You can use the following:
func g(mybool bool) int {
if mybool {
return 3
} else {
return 45
}
}
And I generated a playground for you to test.
As pointed to by Atomic_alarm and the FAQ "There is no ternary form in Go."
As a more general answer to your question of "how to turn a bool into a int" programmers would generally expect true to be 1 and false to be 0, but go doesn't have a direct conversion between bool and int such that int(true)
or int(false)
will work.
You can create the trivial function in this case as they did in VP8:
func btou(b bool) uint8 {
if b {
return 1
}
return 0
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With