英文:
How do I turn a bool into an int?
问题
在Go语言中,没有三元运算符(ternary operator)。但是你可以使用if-else语句来实现相同的功能。你可以这样重写你的代码:
func g(arg bool) int {
if arg {
return 3
} else {
return 45
}
}
这样,如果arg
为true
,则返回3;如果arg
为false
,则返回45。
英文:
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?
答案1
得分: 14
你可以使用以下代码:
func g(mybool bool) int {
if mybool {
return 3
} else {
return 45
}
}
我为你生成了一个playground,供你测试使用。
正如Atomic_alarm和FAQ所指出的,“Go语言中没有三元形式”。
作为对你“如何将bool转换为int”的更一般性回答,程序员通常期望true为1,false为0,但是Go语言没有直接的bool到int的转换方式,因此int(true)
或int(false)
是无法工作的。
你可以像VP8中那样创建一个简单的函数:
func btou(b bool) uint8 {
if b {
return 1
}
return 0
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论