21.8 Underscores and the .. Pattern

Rust provides multiple ways to ignore parts of a value:

  • _: Matches exactly one value, ignoring it.
  • _x: A named variable beginning with _ will not warn if unused but can still be referenced.
  • ..: In a struct or tuple, this syntax ignores all remaining fields or elements not listed explicitly.

21.8.1 Example: Ignoring Fields With ..

struct Point3D {
    x: i32,
    y: i32,
    z: i32,
}

fn classify_point(point: Point3D) {
    match point {
        Point3D { x: 0, .. } => println!("Point is in the y,z-plane"),
        Point3D { y: 0, .. } => println!("Point is in the x,z-plane"),
        Point3D { x, y, .. } => println!("Point is at ({}, {}, ?)", x, y),
    }
}

fn main() {
    let p1 = Point3D { x: 0, y: 5, z: 10 };
    let p2 = Point3D { x: 3, y: 0, z: 20 };
    let p3 = Point3D { x: 2, y: 4, z: 8 };
    classify_point(p1);
    classify_point(p2);
    classify_point(p3);
}

Here, .. makes it clear that any fields not explicitly mentioned are ignored.