【问题标题】:How to match a string against a static &str?如何将字符串与静态 &str 匹配?
【发布时间】:2019-04-14 20:30:16
【问题描述】:

我正在编写一个可能在字符串处理方面做得太多的程序。我将大部分文字信息移至常量;我不确定这是否是 Rust 中的正确方法,但我习惯于用 C 编写。

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

我知道这是一个编译器问题,但不知道如何以 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
        }
    }
}
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

【问题讨论】:

标签: rust pattern-matching match


【解决方案1】:

使用constant 代替静态:

const STATUS_TEST_OK: &str = "PASSED";

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

另见:

【讨论】:

  • 感谢您的解决方案和参考!真的很有帮助!
猜你喜欢
  • 2014-10-12
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-21
  • 2015-08-25
  • 2019-07-18
相关资源
最近更新 更多