How do I turn a bool into an int?

huangapple go评论109阅读模式
英文:

How do I turn a bool into an int?

问题

在Go语言中,没有三元运算符(ternary operator)。但是你可以使用if-else语句来实现相同的功能。你可以这样重写你的代码:

  1. func g(arg bool) int {
  2. if arg {
  3. return 3
  4. } else {
  5. return 45
  6. }
  7. }

这样,如果argtrue,则返回3;如果argfalse,则返回45。

英文:

I'm used to C/Java, where I could use ?: as in:

  1. func g(arg bool) int {
  2. return mybool ? 3 : 45;
  3. }

Since Go does not have a ternary operator,
how do I do that in go?

答案1

得分: 14

你可以使用以下代码:

  1. func g(mybool bool) int {
  2. if mybool {
  3. return 3
  4. } else {
  5. return 45
  6. }
  7. }

我为你生成了一个playground,供你测试使用。

正如Atomic_alarm和FAQ所指出的,“Go语言中没有三元形式”。

作为对你“如何将bool转换为int”的更一般性回答,程序员通常期望true为1,false为0,但是Go语言没有直接的bool到int的转换方式,因此int(true)int(false)是无法工作的。

你可以像VP8中那样创建一个简单的函数:

  1. func btou(b bool) uint8 {
  2. if b {
  3. return 1
  4. }
  5. return 0
  6. }
英文:

You can use the following:

  1. func g(mybool bool) int {
  2. if mybool {
  3. return 3
  4. } else {
  5. return 45
  6. }
  7. }

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:

  1. func btou(b bool) uint8 {
  2. if b {
  3. return 1
  4. }
  5. return 0
  6. }

huangapple
  • 本文由 发表于 2015年7月18日 15:42:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/31488985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定