在Go语言中,if条件中出现了非布尔值。

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

non-bool value in if condition in Go

问题

我在Go语言中有一个if语句,代码如下:

  1. if level & 1 {
  2. // 做某事
  3. } else {
  4. // 做其他事情
  5. }

在我的代码中,level变量的类型是uint。但是当我对1进行按位与操作时,结果并不是布尔值。这在C语言中是有效的语法,但显然在Go语言中不起作用。有没有什么办法可以解决这个问题呢?

英文:

I have an if statement in Go which looks like this:

  1. if level & 1 {
  2. // do something
  3. } else {
  4. // do something else
  5. }

The level variable in my cause is of type uint. But when I do bitwise AND with 1, the result is not a boolean. This is a valid syntax for C, but apparently it doesn't work in Go. Any idea how to work around this?

答案1

得分: 23

在Go语言中,if语句必须具有bool类型的条件表达式,你可以通过使用比较运算符来实现,其结果是一个布尔值:

  1. if level&1 != 0 {
  2. // 做某事
  3. } else {
  4. // 做其他事情
  5. }
英文:

If statements in Go must have type of bool, which you can achieve by using a comparison operator, the result of which is a bool:

  1. if level&1 != 0 {
  2. // do something
  3. } else {
  4. // do something else
  5. }

huangapple
  • 本文由 发表于 2017年8月7日 01:46:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/45534885.html
匿名

发表评论

匿名网友

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

确定