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
  • 388,571
  • 95
  • 1,107
  • 1,366
Muhammad Lukman Low
  • 8,177
  • 11
  • 44
  • 54

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
  • 388,571
  • 95
  • 1,107
  • 1,366
DK.
  • 55,277
  • 5
  • 189
  • 162