首页 > 解决方案 > 匹配 `&str` 的开头

问题描述

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

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

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

标签: rustpattern-matching

解决方案


你可以使用starts_withstr的方法。

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

推荐阅读