TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
&= 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.
- Borrowing vs. Moving:
lhs &= rhsonly borrowslhsmutably. Conversely,lhs = lhs & rhsconsumes (moves)lhsif the type does not implement theCopytrait. - Trait Independence: A type can implement
BitAndAssignwithout implementing theBitAndtrait. Therefore,lhs &= rhscan be perfectly valid even whenlhs = lhs & rhsresults 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 are1, 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.
Trait Implementation
The Rust standard library implements theBitAndAssign 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.
Master Rust with Deep Grasping Methodology!Learn More





