有没有办法将整数转换为布尔或反之亦然? [英] Is there a way to convert integers to bools in go or vice versa?

查看:135
本文介绍了有没有办法将整数转换为布尔或反之亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种内部方法可以将bools投射到整数,反之亦然?我试过正常的投射,但由于他们使用不同的底层类型,转换是不可能的经典方式。我倾注了一些规范,并且还没有找到答案。

解决方案

,只需 x!= 0 就可以了。换句话说,由于Go不支持三元运算符,因此您必须这样做:

  var x int 
如果b {
x = 1
} else {
x = 0
}

你当然可以把它放在一个函数中:

  func Btoi(b bool) int {
if b {
return 1
}
return 0
}

有很多可能的整数布尔解释,它们都不是必然的,所以必须说出你的意思是有意义的。



根据我的经验(YMMV),如果您编写的代码良好,则不必经常执行此操作。它有时候很有吸引力,能够写出一个基于布尔值的数学表达式,但是你的维护者会感谢你避免它。


Is there a builtin way to cast bools to integers or vice versa? I've tried normal casting, but since they use different underlying types, conversion isn't possible the classic way. I've poured over some of the specification, and I haven't found an answer yet.

解决方案

Int to bool is easy, just x != 0 will do the trick. To go the other way, since Go doesn't support a ternary operator, you'd have to do:

var x int
if b {
    x = 1
} else {
    x = 0
}

You could of course put this in a function:

func Btoi(b bool) int {
    if b {
        return 1
    }
    return 0
 }

There are so many possible boolean interpretations of integers, none of them necessarily natural, that it sort of makes sense to have to say what you mean.

In my experience (YMMV), you don't have to do this often if you're writing good code. It's appealing sometimes to be able to write a mathematical expression based on a boolean, but your maintainers will thank you for avoiding it.

这篇关于有没有办法将整数转换为布尔或反之亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆