[英]How to match a string against a static &str?
我正在編寫一個在字符串處理方面可能有點過多的程序。 我將大部分文字信息移至常量; 我不確定這是否是 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
使用const
ant 而不是 static:
const STATUS_TEST_OK: &str = "PASSED";
fn match_out(s: &str) -> bool {
match s {
STATUS_TEST_OK => {
println!("Yes");
true
}
_ => {
println!("No");
false
}
}
}
也可以看看:
對於那些無法將 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.