1

I have this

fn main() {
    let args = os::args();
    let first_args = args[1].to_string();
    match first_args {
        "test" => println!("Good!"),
        _      => println!("No test ?!"),
    }
}

but during compilation, I get this error:

error: mismatched types: expected `collections::string::String`, found `&'static str` (expected struct collections::string::String, found &-ptr)
src/command_line_arguments.rs:7         "test" => println!("Good!"),
                                        ^~~~~~

Can someone please help me to understand this better? What would be a better way of doing this?

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
Muhammad Lukman Low
  • 7,623
  • 9
  • 38
  • 53

1 Answers1

7

There are two kinds of strings in Rust, as explained by the Strings section of the Rust Book. Short version: there's strings that own their contents (String), and strings that don't (&str).

first_args is String, but string literals are &strs (as noted by the error). To do this, you need to turn first_args back into a borrowed string, like so:

fn main() {
    let args = os::args();
    let first_args = args[1].to_string();
    match &*first_args {
        "test" => println!("Good!"),
        _      => println!("No test ?!"),
    }
}

To just clarify what &* does: owning containers (like String and Vec) can "decay" into borrowed references to their contents. * is used to "dereference" the container into its contents (i.e. *first_args takes the String and provides access to the underlying str), whilst the & re-borrows that value, turning it back into a regular reference.

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159
DK.
  • 49,288
  • 3
  • 161
  • 146