2017-08-28 37 views
1

我正在逐行閱讀一些文件,並希望匹配每一行,以驗證它是否包含特定的字符串。如何進一步處理匹配字符串?

我到目前爲止有:

// 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"), 
    } 
} 

回答

3

match使用的if,稱爲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中沒有這樣的語法。