2016-07-12 69 views
1

考慮以下模式匹配時可以使用變量的值而不是綁定嗎?

enum FooBar { 
    Bar, 
    Foo, 
} 

struct Whatever { 
    f_type: FooBar, 
} 

let what = Whatever { f_type: FooBar::Bar }; 

我知道這個工程:

let answer: bool = match what { 
    Whatever { f_type: FooBar::Bar } => true, 
    _ => false, 
}; 
println!("{:?}", answer); // true 

有沒有辦法得到這個工作,使得bar_match用於比較的價值,而不是被綁定到當前值?

let bar_match = FooBar::Bar; 
let answer: bool = match what { 
    Whatever { f_type: bar_match } => true, 
    _ => false, 
}; 
println!("{:?}", answer); // true 

我是Rust noob,但是我無法在網上找到這個問題的答案。

+0

僅供參考,':bool'是多餘的;該類型是由'match'武器的值推斷的。 – Shepmaster

回答

2

你在找什麼叫match guards

如果讓FooBarCopyClone派生和PartialEq你可以建立match guards其值:

let bar_match = FooBar::Bar; 
let answer: bool = match what { 
    Whatever { f_type } if f_type == FooBar::Bar => true, 
    _ => false, 
}; 

Full play.rust-lang.org example.

相關問題