简体   繁体   English

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

[英]How to match a string against a static &str?

I am writing a program that does probably a little bit too much with string processing.我正在编写一个在字符串处理方面可能有点过多的程序。 I moved most of the literal messages to constants;我将大部分文字信息移至常量; I'm not sure if that is the proper way in Rust, but I'm used to writing that in C.我不确定这是否是 Rust 中的正确方法,但我习惯于用 C 编写它。

I figured out that I cannot easily use my static &str inside a match expression.我发现我不能轻易地在match表达式中使用我的static &str I can use the text itself, but cannot figure out how to do that properly.我可以使用文本本身,但无法弄清楚如何正确地做到这一点。

I understand it's a compiler issue, but don't know how to write that construction properly in Rust style.我知道这是一个编译器问题,但不知道如何以 Rust 风格正确编写该构造​​。 Should I use enums instead of C-like static variables?我应该使用枚举而不是类 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
        }
    }
}
error[E0530]: match bindings cannot shadow statics
 --> src/lib.rs:8:9
  |
2 | static STATUS_TEST_OK: &str = "PASSED";
  | --------------------------------------- the static `STATUS_TEST_OK` is defined here
...
8 |         STATUS_TEST_OK => {
  |         ^^^^^^^^^^^^^^ cannot be named the same as a static

For those unable to change the static to a const—although it's a little convoluted—another option is to use an if statement, which will return the &str (or whatever is defined) that lives in the static's NAME:对于那些无法将 static 更改为 const 的人——尽管它有点复杂——另一种选择是使用 if 语句,它将返回位于 static NAME 中的&str (或任何定义的):

static STATUS_TEST_OK: &str = "PASSED";

fn match_out(s: &str) -> bool {

    match s {
        str if str == STATUS_TEST_OK => {
            println!("Yes");
            true
        }
        _ => {
            println!("No");
            false
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM