Match each enum variant explicitly

⚓ Rust    📅 2026-06-04    👤 surdeus    👁️ 4      

surdeus

enum Point {
    Nothing,
    TuplePoint(i32, i32),
    StructPoint {
        x: i32,
        y: i32
    }
}

fn get_point(n: u8) -> Point {
    match n {
        1 => Point::TuplePoint(-1, 1),
        2 => Point::StructPoint {
            x: -1,
            y: 1
        },
        _ => Point::Nothing
    }
}

fn main() {
    let p = get_point(2);
    match p {
        Point :: Nothing => println!("no point"),
        Point :: TuplePoint(x, y) => println!("x is {} and y is {}", x, y),
        Point :: StructPoint{x, y} => println!("x is {} and y is {}", x, y),
    }
}

(Playground)

Output:

x is -1 and y is 1

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.62s
     Running `target/debug/playground`

2 posts - 2 participants

Read full topic

🏷️ Rust_feed