2016-12-30 90 views
2

Rust可以匹配struct字段嗎?例如,下面的代碼:如何匹配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"), 
} 

應導致:

y is true 
+1

你如何提出這個使用...非布爾型字段?例如,如何使用'struct Person {surname:String,age:u8}'來工作? –

回答

5

你的問題沒有任何意義;只需使用一個正常的if聲明:

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

我強烈建議重新閱讀The Rust Programming Language,專門的章節對

一旦你閱讀完了,應該清楚point.x不是一個模式,所以它不能用在比賽手臂的左側。

+0

非常感謝 – maku

10

Rust可以匹配struct字段嗎?

它在Rust書的Destructuring一章中有描述。

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