You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust语言中如何实现字符串切片开头内容的匹配?

方案1:稳定版首选 strip_prefix 匹配

直接调用字符串自带的strip_prefix方法,返回Option类型,可以直接配合if let或者match使用,无需手动处理字节:

fn main() {
    let m = "true other stuff";
    // if let 链写法,分支少时更简洁
    if let Some(_rest) = m.strip_prefix("true") {
        // 匹配true开头的逻辑,_rest是前缀之后的剩余内容,不需要可以忽略
    } else if let Some(_rest) = m.strip_prefix("false") {
        // 匹配false开头的逻辑
    } else {
        panic!("no")
    }
}

如果分支较多,也可以写成嵌套match结构,可读性更高:

fn main() {
    let m = "true other stuff";
    match m.strip_prefix("true") {
        Some(_rest) => { /* 处理true开头的情况 */ },
        None => match m.strip_prefix("false") {
            Some(_rest) => { /* 处理false开头的情况 */ },
            None => panic!("no")
        }
    }
}

方案2:match守卫写法

和原有starts_with逻辑一致,只是包装成match结构,适合习惯用match分支的场景:

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

方案3:nightly 极简前缀匹配

如果你可以使用Rust nightly版本,开启pattern_prefix_suffix特性后可以直接使用前缀匹配语法,完全不需要冗余的方法调用:

#![feature(pattern_prefix_suffix)]

fn main() {
    let m = "true other stuff";
    match m {
        "true".. => { /* 匹配所有以true开头的字符串 */ },
        "false".. => { /* 匹配所有以false开头的字符串 */ },
        _ => panic!("no")
    }
}

这种写法和手动写字节数组匹配的逻辑一致,但编译器会自动处理字符串转码,不需要手动拆成字节,能避免编码错误。


内容的提问来源于stack exchange,提问作者clubby789

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 13:54:00