fn main() {
for arg in std::env::args().skip(1) {
respond(arg);
}
}
fn respond(arg: &str) {
match arg {
"hi" => println!("Hello there!"),
"bye" => println!("OK, goodbye!"),
_ => println!("Sorry, I don't know what {} means", arg),
}
}
Actually, this code wont work, the error will be expected &str, found struct
std::string::String``
I need to get a reference to a str
instead of the String
I got from args(). Easy to fix.
respond(&arg);
But then I realize that the respond function is silly and inline the match
:
fn main() {
for arg in std::env::args().skip(1) {
match &arg {
"hi" => println!("Hello there!"),
"bye" => println!("OK, goodbye!"),
_ => println!("Sorry, I don't know what {} means", arg),
}
}
}
I remember to match on &arg
instead of arg
, so perhaps it should work? but NO
| ^^^^ expected struct `std::string::String`, found str
|
= note: expected type `&std::string::String`
found type `&'static str`
Huh, that's weird. In order to figure out what's going on here, you hae to unserstand quite a few details of the deref magic going on behind the scenes. There are there solutions:
match &*arg {
or
match arg.ar_ref() {
or
match &arg[] {