How to match struct fields in Rust?

两盒软妹~` 提交于 2020-05-12 11:18:20

问题


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

回答1:


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"),
}



回答2:


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

  • enums
  • match
  • patterns

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.



来源:https://stackoverflow.com/questions/41390457/how-to-match-struct-fields-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!