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

Time:11-12

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?

CodePudding user response:

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

changedValue := !value

CodePudding user response:

There's a short answer, written somewhere else :-)

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"

  • Related