Home > Article > Backend Development > How Do Bitwise Operations and Masking Work in Go, and Why Does \'isAdmin & roles == isAdmin\' Evaluate to True?
In Go, bitmasking and bitwise operations provide efficient ways to manipulate binary data. Let's explore how these operations work and clarify your confusion regarding bitmasking.
Bitmasking is a technique that utilizes specially crafted constants to represent different roles or permissions. In your code snippet, you used the iota constant to create a series of constants that each contain a single '1' bit at a specific position. These constants are then used to construct a roles variable using bitwise OR ('|'):
<code class="go">var roles byte = isAdmin | canSeeFinancials | canSeeEurope</code>
This operation sets the '1' bits in roles to match the positions of '1' bits in the three constants. Visualizing the binary representations helps:
isAdmin 00000001 canSeeFinancials 00000100 canSeeEurope 00100000 ------------------------- roles 00100101
Your confusion arises from the bitwise AND ('&') operation used in this line:
<code class="go">fmt.Printf("Is Admin? %v\n", isAdmin & roles == isAdmin)</code>
This operation checks if isAdmin is set in the roles variable. However, the expression isAdmin & roles returns a number that contains '1' bits only where both isAdmin and roles have '1' bits.
In your case, since roles includes the isAdmin bit, the result of isAdmin & roles will be equal to isAdmin. That's why the expression evaluates to true.
However, if you use the less stringent bitwise equality (==), you're comparing the entire binary representation of roles to isAdmin. Since roles contains additional bits, it is not equal to isAdmin, resulting in false.
Bitmasking and bitwise operations are powerful tools that allow you to perform logical operations on binary data efficiently. By understanding the concepts behind bit manipulation, you can write more robust and efficient code in Go.
The above is the detailed content of How Do Bitwise Operations and Masking Work in Go, and Why Does \'isAdmin & roles == isAdmin\' Evaluate to True?. For more information, please follow other related articles on the PHP Chinese website!