我如何将布尔值转换为整数? [重复]
问题描述:
This question already has an answer here:
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?
</div>
此问题已经存在 在这里有一个答案: p>
-
是否可以将整数转换为go,反之亦然?
5个答案
span>
li>
ul>
div>
我习惯于C / Java,可以在其中使用?:,例如: p>
func g(arg bool)int { return mybool吗? 3:45; } code> pre>
自 Go没有三元运算符, 如何在go中执行此操作? p> div>
答
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
}