Skip to content

Instantly share code, notes, and snippets.

@aucker
Last active March 14, 2023 02:38
Show Gist options
  • Save aucker/8fd3d1aec04ed0ef2440c7d484a361d7 to your computer and use it in GitHub Desktop.
Save aucker/8fd3d1aec04ed0ef2440c7d484a361d7 to your computer and use it in GitHub Desktop.
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[] {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment