简体   繁体   中英

How to match struct fields in Rust?

Can Rust match struct fields? For example, this code:

struct Point {
    x: bool,
    y: bool,
}

let point = Point { x: false, y: true };

match point {
    point.x => println!("x is true"),
    point.y => println!("y is true"),
}

Should result in:

y is true

Can Rust match struct fields?

It is described in the Rust book in the "Destructuring structs" chapter.

match point {
    Point { x: true, .. } => println!("x is true"),
    Point { y: true, .. } => println!("y is true"),
    _ => println!("something else"),
}

The syntax presented in your question doesn't make any sense; it seems that you just want to use a normal if statement:

if point.x { println!("x is true") }
if point.y { println!("y is true") }

I'd highly recommend re-reading The Rust Programming Language , specifically the chapters on

Once you've read that, it should become clear that point.x isn't a pattern, so it cannot be used on the left side of a match arm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM