[英]How to pattern match a String in a struct against a literal
在下面的代码中,我发现match_num_works()
中的代码具有一定的风格。 我想编写一个具有类似公式的String
匹配项,但无法使其正常工作。 我最终得到了match_text_works()
,它不太优雅。
struct FooNum {
number: i32,
}
// Elegant
fn match_num_works(foo_num: &FooNum) {
match foo_num {
&FooNum { number: 1 } => (),
_ => (),
}
}
struct FooText {
text: String,
}
// Clunky
fn match_text_works(foo_text: &FooText) {
match foo_text {
&FooText { ref text } => {
if text == "pattern" {
} else {
}
}
}
}
// Possible?
fn match_text_fails(foo_text: &FooText) {
match foo_text {
&FooText { text: "pattern" } => (),
_ => (),
}
}
它可能不是“优雅”的或更好的..但是一种选择是将条件移到match表达式中:
match foo_text {
&FooText { ref text } if text == "pattern" => (),
_ => ()
}
请注意,您想要的模式实际上可以与&str
。 您不能直接对String
模式匹配,因为它是一个更复杂的值,其中包括未暴露的内部缓冲区。
struct FooText<'a> {
text: &'a str,
_other: u32,
}
fn main() {
let foo = FooText { text: "foo", _other: 5 };
match foo {
FooText { text: "foo", .. } => println!("Match!"),
_ => println!("No match"),
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.