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 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解