如何匹配字符串的开头?

Jam*_*ger 5 pattern-matching rust

我想在字符串切片的开头执行匹配。我目前的做法是:

fn main() {
    let m = "true other stuff";
    if m.starts_with("true") { /* ... */ } 
    else if m.starts_with("false") { /* ... */ }
}

Run Code Online (Sandbox Code Playgroud)

但这比我喜欢的更冗长。另一种方法是:

fn main() {
    match "true".as_bytes() {
        [b't', b'r', b'u', b'e', ..] => { /* ... */ },
        [b'f', b'a', b'l', b's', ,'e', ..] => { /* ... */ },
        _=> panic!("no")
    }
}

Run Code Online (Sandbox Code Playgroud)

但我不想将每个模式手动写为字节数组。这里有更好的方法吗?

Ayk*_*maz 8

starts_with您可以在 match 语句中使用str 方法。

fn main() {
    match "true" {
        s if s.starts_with("true") => { /* ... */ },
        s if s.starts_with("false") => { /* ... */ },
        _ => panic!("no")
    }
}
Run Code Online (Sandbox Code Playgroud)