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
.
&str
is a reference, not a value.if
comparison but not with amatch
.if
statement delegates to thePartialEq
implementation. Thematch
doesn'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. Theif
conditional becomes a simple branch whereas thematch
does appear (according to the LLVM IR) to be somewhat of aswitch
when compiled down.if else
is a perfectly fine construct to use.