Rust可以匹配struct字段吗?例如,这段代码:
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"),
}
Run Code Online (Sandbox Code Playgroud)
应该导致:
y is true
Run Code Online (Sandbox Code Playgroud)
aSp*_*pex 25
Rust可以匹配struct字段吗?
它在Rust书中的"Destructuring structs"一章中有所描述.
match point {
Point { x: true, .. } => println!("x is true"),
Point { y: true, .. } => println!("y is true"),
_ => println!("something else"),
}
Run Code Online (Sandbox Code Playgroud)
你问题中提出的语法没有任何意义; 看来你只想使用正常的if
声明:
if point.x { println!("x is true") }
if point.y { println!("y is true") }
Run Code Online (Sandbox Code Playgroud)
我强烈建议重新阅读Rust编程语言,特别是章节
一旦你读完它,就应该清楚它point.x
不是一个模式,所以不能在匹配臂的左侧使用它.
归档时间: |
|
查看次数: |
5396 次 |
最近记录: |