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 as either a unary address-of operator or a binary bitwise AND operator, depending on the lexical context and the number of operands.

Unary Operator: Address-Of

When used as a unary operator preceding a single operand, & generates a pointer to that operand. If the operand x is of a defined type (e.g., int), the expression &x yields a pointer value of type *int containing the memory address of x.
func addressOfExample() {
    var x int
    p := &x  // p is of type *int
    _ = p    // Blank identifier used to satisfy the compiler
}
Addressability Requirements: The operand must be addressable. According to the Go specification, addressable operands include:
  • Variables
  • Pointer indirections (*p)
  • Slice indexing operations (s[i])
  • Field selectors of addressable structs (obj.field)
  • Array indexing operations of addressable arrays (arr[i])
The & operator cannot be applied to unaddressable values, such as:
  • Constants
  • Basic literal values (e.g., &42 or &"string")
  • Map elements (m[key])
  • Return values of function or method calls
Composite Literals: As a syntactic exception, the & operator can be applied directly to a composite literal. This operation evaluates the literal, allocates memory for it on the heap or stack, and returns a pointer to the newly allocated value. It is semantically equivalent to using the built-in new function followed by initialization.
type Config struct { 
    F int 
}

func compositeLiteralExample() {
    // Allocates a Config and returns *Config
    p := &Config{F: 1} 
    _ = p
}

Binary Operator: Bitwise AND

When used as a binary operator between two operands, & performs a bitwise AND operation. It evaluates the binary representations of both operands and returns a new value where each bit is 1 only if the corresponding bits in both operands are 1.
func bitwiseAndExample() {
    var a int = 12
    var b int = 10
    c := a & b
    _ = c
}
Type Constraints:
  • Both operands must be of the same integer type (e.g., int, uint8, int64), or both must be untyped constants that can be implicitly converted to a common integer type.
  • If one operand is a typed integer and the other is an untyped constant, the untyped constant is implicitly converted to the type of the typed operand (e.g., var a int8 = 5; c := a & 1 is valid and yields an int8).
  • The & operator cannot be applied to floating-point numbers, complex numbers, or non-numeric types.
  • The resulting value shares the same integer type as the operands.
Master Go with Deep Grasping Methodology!Learn More