首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将字符串与静态字符串进行匹配?

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

Stack Overflow用户
提问于 2019-04-15 04:30:17
回答 1查看 1.2K关注 0票数 1

我正在写一个程序,它可能在字符串处理方面做得有点过了。我将大多数文字消息移动到常量;我不确定在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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-15 04:36:12

使用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
        }
    }
}

另请参阅:

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55679758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档