匹配 `&str` 的开头

问题描述

我想对字符串切片的 start 执行匹配。我目前的做法是

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

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

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

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

解决方法

您可以使用 str 的 starts_with 方法。

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