如何匹配字符串以进行进一步处理?

时间:2017-08-28 09:45:35

标签: string rust match

我正在逐行读取某个文件并希望匹配每一行,以验证它是否包含特定的字符串。

到目前为止我所拥有的:

// read file line by line
let file = File::open(file_path).expect("Cannot open file");
let buffer = BufReader::new(file);
for line in buffer.lines() {
    // println!("{:?}", line.unwrap());
    parse_line(line.unwrap());

}

fn parse_line(line: String) {
    match line {
        (String) if line.contains("foo") => print!("function head"),
        _ => print!("function body"),
    }
}

这导致:

error: expected one of `,` or `@`, found `)`
  --> src/main.rs:13:20
   |
13 |             (String) if line.contains("foo") => print!("function head"),
   |                    ^ expected one of `,` or `@` here

我是否可以使用match来检查不同的包含字符串,就像我在其他情况下使用switch一样?

如同:

fn parse_line(line: String) {
    match line {
        line.contains("foo") => print!("function foo"),
        line.contains("bar") => print!("function bar"),
        _ => print!("function body"),
    }
}

1 个答案:

答案 0 :(得分:3)

if中使用match,称为match guard

fn main() {
    use std::fs::File;
    use std::io::BufReader;
    use std::io::BufRead;

    let file_path = "foo.txt";
    // read file line by line
    let file = File::open(file_path).expect("Cannot open file");
    let buffer = BufReader::new(file);
    for line in buffer.lines() {
        parse_line(line.unwrap());
    }
}

fn parse_line(line: String) {
    match line {
        ref s if s.contains("foo")  => print!("contains foo"),
        ref s if s.contains("bar")  => print!("contains bar"),
        _                           => print!("other"),
    }
}

注意这一行:

(String) if line.contains("foo") => print!("function head");

不是Rust。在Rust中没有类似的语法。