如何将布尔值从true更改为false,反之亦然

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

How to alter Boolean value from true to false and vice-versa

问题

我在Go语言中有一个要求,需要修改布尔值并将其存储起来。
我收到的值是true,但我需要修改它并存储修改后的值。
我只能想到将修改后的值存储到一个变量中,并在下一条语句中传递它。

伪代码示例:

changevalue := false

if value == false {
     changevalue = true 
}

在Go语言中,有什么最好的方法来实现这个?是否有预定义的方法可以做到这一点?

英文:

I have a requirement in Go of altering the bool value and store it.
I am receiving value == true but I need to alter it and store the altered value.
I can think of only storing the alerted to a var and pass it in the next statement.

Eg psuedo code:

chnagevalue := false

if value == false {
     changevalue == true 
}

what's the best way to do it in Go? Is there any pre-defined way to do it?

答案1

得分: 5

使用逻辑非运算符 ! 将 true 转换为 false,反之亦然:

changedValue := !value
英文:

Use the logical NOT operator ! to change true to false and vice versa:

changedValue := !value

答案2

得分: 1

有一个简短的答案,写在别的地方 如何将布尔值从true更改为false,反之亦然

你的代码几乎也是正确的:

changedValue := false

if !value {
     changedValue == true 
}

if语句总是关于某个条件是否为真。所以上面的代码可以理解为:如果一个值等于false,则为真,然后执行{}中的代码块。

当然,你的思维方式更简洁:
如果一个值等于false,则执行{}中的代码块。

而使用switch语句则更好:

changedValue := !changedValue

顺便说一下:我永远不会使用类似"changedValue"这样的字段名,因为...
每个变量都是某种类型的值,所以没有必要写出来。

"changed"应该足够了。
或者,当它是一个布尔值时,更好的选择是:
"isChanged"或"hasChanged"。

英文:

There's a short answer, written somewhere else 如何将布尔值从true更改为false,反之亦然

Yours is almost good too:

changedValue := false

if !value {
     changedValue == true 
}

An if statement is always about something being true.
so in the above it reads : if a value equals false is true then {}.

of course your mind reads it the short way :
if a value equals false then {}.

the switch of course works the best:

changedValue := !changedValue

BTW: I would never use a fieldname like "changedValue" because...
every variable is a value of some kind, so there is no need of writing that.

"changed" should be enough.
or, when it is a boolean like this , even better:
"isChanged" or "hasChanged"

huangapple
  • 本文由 发表于 2021年11月11日 13:41:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/69923678.html
匿名

发表评论

匿名网友

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

确定