dongye6377 2015-07-18 07:42
浏览 60
已采纳

我如何将布尔值转换为整数? [重复]

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>
  • 写回答

1条回答 默认 最新

  • dongpao5658 2015-07-18 08:03
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图