简体   繁体   English

如何对字面上的结构进行字符串模式匹配

[英]How to pattern match a String in a struct against a literal

In my code below I find that the code in match_num_works() has a certain elegance. 在下面的代码中,我发现match_num_works()中的代码具有一定的风格。 I would like to write a String match with a similar formulation but cannot get it to work. 我想编写一个具有类似公式的String匹配项,但无法使其正常工作。 I end up with match_text_works() which is less elegant. 我最终得到了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" } => (),
        _ => (),
    }
}

Its probably not "elegant" or any nicer.. but one option is to move the conditional into the match expression: 它可能不是“优雅”的或更好的..但是一种选择是将条件移到match表达式中:

match foo_text {
    &FooText { ref text } if text == "pattern" => (),
    _ => ()
}

Working sample: Playpen link . 工作示例:Playpen链接

Note that your desired pattern would actually work with a &str . 请注意,您想要的模式实际上可以与&str You can't directly pattern match a String because it's a more complex value that includes an unexposed internal buffer. 您不能直接对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"),
    }
}

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM