有没有办法在Go语言中将整数转换为布尔值,或者反之亦然?

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

Is there a way to convert integers to bools in go or vice versa?

问题

有没有一种内置的方法可以将布尔值转换为整数或反之亦然?我尝试过普通的转换,但由于它们使用不同的底层类型,无法以经典的方式进行转换。我已经仔细研究了一些规范,但还没有找到答案。

英文:

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.

答案1

得分: 59

将整数转换为布尔值很简单,只需使用x != 0即可。要反过来转换,由于Go语言不支持三元运算符,你需要这样做:

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

当然,你可以将其放在一个函数中:

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

整数有很多可能的布尔解释,它们都不一定是自然的,所以有必要明确表达你的意思。

根据我的经验(可能因人而异),如果你编写良好的代码,通常不需要经常这样做。有时候,根据布尔值编写数学表达式很有吸引力,但是你的维护者会感谢你避免这样做。

英文:

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.

答案2

得分: 22

这里有一个将int转换为bool的技巧:

x := 0
newBool := x != 0 // 返回 false

其中x是你想要转换的int变量。

英文:

Here's a trick to convert from int to bool:

x := 0
newBool := x != 0 // returns false

where x is the int variable you want to convert from.

答案3

得分: 10

var a int = 3
var b bool = a != 0

我刚刚把这段代码放到了golang首页上的demo框中:

package main

import "fmt"

func main() {
 var a int = 3
 var b bool = a != 0
 fmt.Println("Hello, 世界", b)
}

输出结果:

Hello, 世界 true
英文:
var a int = 3
var b bool = a != 0

I just dropped this into the demo box on the golang front page:

package main

import "fmt"

func main() {
 var a int = 3
 var b bool = a != 0
	fmt.Println("Hello, 世界", b)
}

Output:

Hello, 世界 true

答案4

得分: 10

bool到整数类型或反之亦然,没有转换

使用不等运算符将整数转换为bool值:

b := i != 0

使用if语句将bool转换为整数类型:

var i int
if b {
    i = 1
}

因为整数类型的零值是0,所以其他答案中显示的else分支是不必要的。

英文:

There are no conversions from bool to integer types or vice versa.

Use the inequality operator to convert integers to bool values:

b := i != 0

Use an if statement to convert a bool to an integer type:

var i int
if b {
    i = 1
}

Because the zero value for integer types is 0, the else branch shown in other answers is not necessary.

答案5

得分: 9

只是为了展示TMTOWTDT

package main

import (
    "fmt"
    "unsafe"
)

func main() {
    fmt.Println(bool2int(true))
    fmt.Println(bool2int(false))
}

func bool2int(a bool) uint64 {
    return *(*uint64)(unsafe.Pointer(&a))&1
}
英文:

Just to show TMTOWTDT

package main

import (
	"fmt"
	"unsafe"
)

func main() {
	fmt.Println(bool2int(true))
	fmt.Println(bool2int(false))
}

func bool2int(a bool) uint64 {
    return *(*uint64)(unsafe.Pointer(&a))&1
}

https://play.golang.org/p/eULE6cJO_c0

答案6

得分: 1

你可以使用映射:

package main

var (
   isZero = map[int]bool{0: true}
   intVal = map[bool]int{true: 1}
)

func main() {
   println(isZero[-2]) // false
   println(isZero[-1]) // false
   println(isZero[0]) // true
   println(isZero[1]) // false
   println(isZero[2]) // false
   
   println(intVal[false]) // 0
   println(intVal[true]) // 1
}
英文:

You could use maps:

package main

var (
   isZero = map[int]bool{0: true}
   intVal = map[bool]int{true: 1}
)

func main() {
   println(isZero[-2]) // false
   println(isZero[-1]) // false
   println(isZero[0]) // true
   println(isZero[1]) // false
   println(isZero[2]) // false
   
   println(intVal[false]) // 0
   println(intVal[true]) // 1
}

答案7

得分: 0

要将布尔值转换为数字类型,最好的方法是使用if语句。请参考@MuffinTop的非常好的答案和https://stackoverflow.com/a/38627381/12817546。同样适用于将布尔值转换为布尔和字符串类型。

package main

import (
	. "fmt"
	. "strconv"
)

func main() {
	var e []interface{}
	t := true
	if t {
		by := []byte{'G', 'o'}
		r := []rune{rune(by[0]), 111}
		f := 70.99
		s := Sprintf("%.f", f)
		i, _ := Atoi(s) // Atoi "ASCII to integer"
		bo := !(t == true)
		// var bo bool = t != true
		e = []interface{}{by[0], r[0], f, s, i, bo}
	}
	checkType(e)
}

func checkType(s []interface{}) {
	for k, _ := range s {
		// uint8 71, int32 71, float64 70.99, string 71, int 71, bool false
		Printf("%T %v\n", s[k], s[k])
	}
}

你可以使用bo := !(t == true)(如@SamehShara所说)或var bo bool = t != true(如@MattJoiner所说)来设置布尔值。在这里,将值为true的布尔值t设置为值为false的布尔值bo

要将truefalse布尔值转换为字符串"true""false",请使用fmt.Sprintf("%v", t)。请参考https://stackoverflow.com/a/47413424/12817546。要进行相反的转换,请使用strconv.ParseBool("true")。请参考https://stackoverflow.com/a/53093945/12817546。引号已编辑。

英文:

To set a numeric type from a bool, the if statement is the best you can do. See @MuffinTop very-good answer and https://stackoverflow.com/a/38627381/12817546. This is also true for setting boolean and string types from a bool.

package main

import (
	. "fmt"
	. "strconv"
)

func main() {
	var e []interface{}
	t := true
	if t {
		by := []byte{'G', 'o'}
		r := []rune{rune(by[0]), 111}
		f := 70.99
		s := Sprintf("%.f", f)
		i, _ := Atoi(s) // Atoi "ASCII to integer"
		bo := !(t == true)
		// var bo bool = t != true
		e = []interface{}{by[0], r[0], f, s, i, bo}
	}
	checkType(e)
}

func checkType(s []interface{}) {
	for k, _ := range s {
		// uint8 71, int32 71, float64 70.99, string 71, int 71, bool false
		Printf("%T %v\n", s[k], s[k])
	}
}

You can use bo := !(t == true) as @SamehShara said or var bo bool = t != true as @MattJoiner said to set a bool. Here t a bool with a value of true is set to bo a bool with a value of false.

To set a "true" or "false" string from a true or false bool use fmt.Sprintf("%v", t). See https://stackoverflow.com/a/47413424/12817546. strconv.ParseBool("true") for the reverse. See https://stackoverflow.com/a/53093945/12817546. Quotes edited.

huangapple
  • 本文由 发表于 2011年12月6日 08:40:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/8393933.html
匿名

发表评论

匿名网友

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

确定