Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Go have a "bit clear (AND NOT)" operator?

Why does Go have &^, the "bit clear (AND NOT)" operator?

Is there ever any difference between a &^ b and a & ^b?

like image 672
user200783 Avatar asked May 04 '17 11:05

user200783


1 Answers

There's a subtle difference that makes dealing with literals and untyped constants easier with the explicit bit clear operator.

Untyped integers have their default type as int so something like a := uint32(1) & ^1 is illegal as ^1 is evaluated first and it's evaluated as ^int(1), which equals -2. a := uint32(1) &^ 1 is legal however as here 1 is evaluated as uint32, based on the context.

There could also be some performance gains in having an explicit bit clear, but I'm not too sure about that.

like image 174
jussius Avatar answered Oct 17 '22 23:10

jussius