如何在 Rust 中通过 match 将 String 与字符串字面量进行匹配?
大家好!我刚开始学习 Rust,在使用 match 比较 String 时遇到了问题。我有一个 String 类型的变量,想检查它是否等于某个字符串字面量。例如,我写了一个简单的命令解析器:
```rust
fn main() {
let command = String::from("start");
match command {
"start" => println!("启动!"),
"stop" => println!("停止!"),
_ => println!("未知命令"),
}
}
```
但编译器报错:
```
error[E0308]: mismatched types
expected struct `String`, found `&str`
```
我知道 String 和 &str 是不同的类型,但如何正确编写 match?我试过用 as_str(),但不确定这是否是最佳方式。也听说可以将字面量转换为 String,但这似乎效率不高。请问如何在 Rust 中正确地将 String 与字符串字面量进行匹配?有没有惯用的方法或最佳实践?谢谢!