gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:15:32 28 4
gpt4 key购买 nike

我正在编写一个程序,它在字符串处理方面可能做的有点多。我将大部分文字消息移至常量;我不确定这是否是 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

最佳答案

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

另见:

关于rust - 如何将字符串与静态 &str 匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679758/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com