I'm trying to implement a function that reads command line arguments and compares them to hard-coded string literals.
When I do the comparison with an if statement it works like a charm:
fn main() {
let s = String::from("holla!");
if s == "holla!" {
println!("it worked!");
}
}
But using a match statement (which I guess would be more elegant):
fn main() {
let s = String::from("holla!");
match s {
"holla!" => println!("it worked!"),
_ => println!("nothing"),
}
}
I keep getting an error from the compiler that a String was expected but a &static str was found:
error[E0308]: mismatched types
--> src/main.rs:5:9
|
5 | "holla!" => println!("it worked!"),
| ^^^^^^^^ expected struct `std::string::String`, found reference
|
= note: expected type `std::string::String`
found type `&'static str`
I've seen How to match a String against string literals in Rust? so I know how to fix it, but I want to know why the comparison works when if but not using match.
&stris a reference, not a value.ifcomparison but not with amatch.ifstatement delegates to thePartialEqimplementation. Thematchdoesn't have this special handling in the compiler and therefore requires a bit of help. The two constructs are compiled differently anyway so I'm not sure how this would work for the internals of the compiler. Theifconditional becomes a simple branch whereas thematchdoes appear (according to the LLVM IR) to be somewhat of aswitchwhen compiled down.if elseis a perfectly fine construct to use.