How to match a String with string literals in Rust using match?
Hello everyone! I just started learning Rust and encountered a problem when using match to compare String. I have a variable of type String, and I want to check if it equals some string literal. For example, I'm writing a simple command parser:
```rust
fn main() {
let command = String::from("start");
match command {
"start" => println!("Start!"),
"stop" => println!("Stop!"),
_ => println!("Unknown command"),
}
}
```
But the compiler gives an error:
```
error[E0308]: mismatched types
expected struct `String`, found `&str`
```
I understand that String and &str are different types, but how do I write the match correctly? I tried using as_str(), but I'm not sure if that's the best way. I also heard that you can convert the lit
No answers yet.
Log in to leave an answer
Blogs