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 is a compound assignment operator that performs a bitwise AND operation (or logical AND for booleans) between a mutable left-hand side (LHS) operand and a right-hand side (RHS) operand, updating the LHS operand in place with the result. Unlike some languages where lhs &= rhs is syntactic sugar for lhs = lhs & rhs, Rust treats compound assignment as a distinct operation. The &= operator desugars directly to a method call on the std::ops::BitAndAssign trait.
// Standard syntax
lhs &= rhs;

// Desugared equivalent
std::ops::BitAndAssign::bitand_assign(&mut lhs, rhs);
This distinction is critical in Rust’s ownership and type system:
  • Borrowing vs. Moving: lhs &= rhs only borrows lhs mutably. Conversely, lhs = lhs & rhs consumes (moves) lhs if the type does not implement the Copy trait.
  • Trait Independence: A type can implement BitAndAssign without implementing the BitAnd trait. Therefore, lhs &= rhs can be perfectly valid even when lhs = lhs & rhs results in a compiler error.

Technical Mechanics

At the bit level, the operator compares each corresponding bit of the LHS and RHS operands. If both bits are 1, the resulting bit is 1. Otherwise, the resulting bit is 0. When applied to boolean types (bool), &= functions as a logical AND assignment, evaluating to true only if both the current LHS value and the RHS value are true. The LHS variable must be explicitly declared as mutable (mut) for the compiler to allow the assignment.
// Integer bitwise AND assignment
let mut a: u8 = 0b1100_1100;
let b: u8     = 0b1010_1010;

a &= b; 

assert_eq!(a, 0b1000_1000);

// Boolean AND assignment
let mut flag = true;
flag &= false;

assert_eq!(flag, false);

Trait Implementation

The Rust standard library implements the BitAndAssign trait for all primitive integer types and booleans. To use &= with custom structs or enums, you must explicitly implement std::ops::BitAndAssign for your type. The trait requires the implementation of a single method, bitand_assign, which takes a mutable reference to self and consumes the RHS operand.
use std::ops::BitAndAssign;

#[derive(Debug, PartialEq)]
struct BitVector(u16);

impl BitAndAssign for BitVector {
    fn bitand_assign(&mut self, rhs: Self) {
        // Mutate self in place
        self.0 &= rhs.0;
    }
}

let mut v1 = BitVector(0b1111);
let v2 = BitVector(0b0101);

v1 &= v2;

assert_eq!(v1, BitVector(0b0101));
Master Rust with Deep Grasping Methodology!Learn More