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

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

问题描述

有没有内置的方法可以将 bool 转换为整数,反之亦然?我尝试过正常的转换,但由于它们使用不同的底层类型,因此无法以经典方式进行转换.我已经倾注了一些规范,但我还没有找到答案.

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 很容易,只要 x != 0 就可以了.反过来,由于 Go 不支持三元运算符,您必须这样做:

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.

根据我的经验 (YMMV),如果您正在编写好的代码,则不必经常这样做.有时能够根据布尔值编写数学表达式很有吸引力,但您的维护人员会感谢您避免使用它.

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.

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

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