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 | (pipe) token in Rust serves three distinct syntactical and semantic functions depending on its lexical context: as a bitwise inclusive OR operator, as an alternation delimiter in pattern matching, and as the parameter enclosure for closures.

1. Bitwise Inclusive OR Operator

When applied to integer or boolean types, | performs a bitwise inclusive OR operation. It evaluates to 1 for each bit position where at least one of the operands has a 1. At the type-system level, this operation is governed by the std::ops::BitOr trait. Types implementing this trait define the behavior of the | operator. The compound assignment variant, |=, is governed by the std::ops::BitOrAssign trait.
let a: u8 = 0b1010_0000;
let b: u8 = 0b0000_1111;

// Bitwise OR operation
let c: u8 = a | b; // Evaluates to 0b1010_1111

2. Pattern Alternation

In pattern matching contexts (match arms, if let, while let, and let statements), the | token acts as a logical OR for patterns. It allows a single execution path to respond to multiple distinct structural matches. A strict compiler constraint applies here: if the pattern binds variables, every alternative separated by | must bind the exact same set of variables, and those variables must have identical types across all alternatives.
enum Status {
    Active(i32),
    Pending(i32),
    Inactive,
}

let status = Status::Active(42);

match status {
    // Alternation with structural binding
    // Both sides of the `|` must bind the variable `val` with the exact same type
    Status::Active(val) | Status::Pending(val) => println!("Value: {}", val),
    
    Status::Inactive => (),
}

let x = 2;

match x {
    // Pattern alternation matching multiple literal values
    1 | 2 | 3 => println!("Matched a low integer"),
    _ => (),
}

3. Closure Parameter Delimiter

Rust uses the | token to enclose the parameter list of an anonymous function (closure). This syntax replaces the parentheses () used in standard fn declarations. The parameters between the pipes can have explicit type annotations or rely on the compiler’s type inference. If a closure takes no arguments, it is denoted by two adjacent pipes ||.
// Inferred types
let add = |a, b| a + b;

// Explicit type annotations and return type
let multiply = |a: i32, b: i32| -> i32 { 
    a * b 
};

// Zero parameters
let execute = || println!("Executed");
Master Rust with Deep Grasping Methodology!Learn More