Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The & operator in Go functions in two distinct capacities depending on its arity: as a unary address-of operator to generate pointers, and as a binary bitwise AND operator for integer manipulation.

Unary Address-Of Operator

When used as a prefix unary operator (&x), & yields the memory address of its operand, producing a pointer value. If the operand is of type T, the resulting pointer is of type *T. Addressability Rules: The operand must be addressable. Valid addressable operands include variables, pointer indirections, slice indexing operations, and struct field selectors. The & operator cannot be applied to unaddressable values, such as basic type literals, constants (whether typed or untyped), map elements, or the direct return values of functions. Composite Literal Exception: According to the Go specification, composite literals are technically unaddressable. However, applying the & operator to a composite literal is a special language exception. When evaluated, it causes the compiler to allocate a new hidden variable of that type, initialize it with the literal’s values, and return the memory address of that newly allocated variable.
var val int = 42
var ptr *int = &val // ptr is of type *int, holding the memory address of val

type MyStruct struct {
    Field int
}

// Composite literal address-of syntax allocates a hidden variable
var structPtr *MyStruct = &MyStruct{Field: 1} 

Binary Bitwise AND Operator

When used as an infix binary operator (x & y), & performs a bitwise AND operation on two integer operands. It evaluates the binary representation of both operands and returns a new integer where each bit is set to 1 only if the corresponding bits in both operands are also 1. Otherwise, the bit is set to 0. Type Constraints: Both operands must resolve to identical integer types (or be untyped constants representable as integers). Floating-point numbers, complex numbers, and non-numeric types are invalid operands for this operation.
var a uint8 = 0b10101100 // Decimal: 172
var b uint8 = 0b00001111 // Decimal: 15
var c uint8 = a & b      // Result: 0b00001100 (Decimal: 12)

Bit Clear (AND NOT) Operator

Go also combines & with the bitwise XOR/complement operator ^ to form a distinct binary operator: the bit clear operator (&^). This operator clears bits in the left operand where the corresponding bit in the right operand is 1. It is mechanically equivalent to x & (~y) in other C-family languages (such as C, C++, Java, and C#), where ~ represents the unary bitwise complement.
var x uint8 = 0b10101100
var y uint8 = 0b00001111
var z uint8 = x &^ y     // Result: 0b10100000
Master Go with Deep Grasping Methodology!Learn More