如何将字符串与静态 &str 进行匹配?

Maz*_*ryt 2 pattern-matching match rust

我正在编写一个程序,它的字符串处理功能可能有点太多了。我将大部分文字消息移至常量;我不确定这在 Rust 中是否正确,但我习惯用 C 编写。

我发现我不能轻易地使用我的static &str内部match表达式。我可以使用文本本身,但不知道如何正确地做到这一点。

我知道这是一个编译器问题,但不知道如何以 Rust 风格正确编写该结构。我应该使用枚举而不是类似 C 的静态变量吗?

static SECTION_TEST: &str = "test result:";
static STATUS_TEST_OK: &str = "PASSED";

fn match_out(out: &String) -> bool {
    let s = &out[out.find(SECTION_TEST).unwrap() + SECTION_TEST.len()..];

    match s {
        STATUS_TEST_OK => {
            println!("Yes");
            true
        }
        _ => {
            println!("No");
            false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)
static SECTION_TEST: &str = "test result:";
static STATUS_TEST_OK: &str = "PASSED";

fn match_out(out: &String) -> bool {
    let s = &out[out.find(SECTION_TEST).unwrap() + SECTION_TEST.len()..];

    match s {
        STATUS_TEST_OK => {
            println!("Yes");
            true
        }
        _ => {
            println!("No");
            false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

She*_*ter 8

使用constant 而不是 static:

const STATUS_TEST_OK: &str = "PASSED";

fn match_out(s: &str) -> bool {
    match s {
        STATUS_TEST_OK => {
            println!("Yes");
            true
        }
        _ => {
            println!("No");
            false
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

也可以看看:


归档时间:

查看次数:

3472 次

最近记录:

3 年,8 月 前