String 如何将结构中的字符串与文本进行模式匹配
在下面的代码中,我发现String 如何将结构中的字符串与文本进行模式匹配,string,struct,rust,match,String,Struct,Rust,Match,在下面的代码中,我发现match\u num\u works()中的代码有一定的优雅。我想用类似的公式编写一个字符串匹配,但无法使其工作。我最终得到的是match\u text\u works(),它不那么优雅 struct FooNum { number: i32, } // Elegant fn match_num_works(foo_num: &FooNum) { match foo_num { &FooNum { number: 1 }
match\u num\u works()
中的代码有一定的优雅。我想用类似的公式编写一个字符串
匹配,但无法使其工作。我最终得到的是match\u text\u 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 foo_text {
&FooText { ref text } if text == "pattern" => (),
_ => ()
}
.它可能并不“优雅”或更好。。但一种选择是将条件移动到匹配表达式中:
match foo_text {
&FooText { ref text } if text == "pattern" => (),
_ => ()
}
.请注意,所需的模式实际上可以与
&str
一起使用。不能直接对字符串进行模式匹配,因为它是一个更复杂的值,包含一个未公开的内部缓冲区
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"),
}
}
struct FooText println!(“比赛!”),
_=>println!(“不匹配”),
}
}
请注意,所需的模式实际上可以与&str
一起使用。不能直接对字符串进行模式匹配,因为它是一个更复杂的值,包含一个未公开的内部缓冲区
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"),
}
}
struct FooText println!(“比赛!”),
_=>println!(“不匹配”),
}
}
谢谢!好的,谢谢!那就行了。