3

I am a Rust beginner and I can't solve this type problem. I have tried replacing &name with name, but the error "pattern &_ not covered" occurred.

fn get_project(name: &'static str) {
    match &name {
        "hi" => {},
    }
}

fn main() {
    let project = get_project("hi");
}

Compiler error:

error[E0308]: mismatched types
 --> <anon>:3:9
  |
3 |         "hi" => {},
  |         ^^^^ expected &str, found str
  |
  = note: expected type `&&str`
  = note:    found type `&'static str`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
maku
  • 465
  • 1
  • 4
  • 7

2 Answers2

6

String literals – like "hi" – have the type &'static str. So if you already have a &str, you don't need to add the &:

fn get_project(name: &str) {
    match name {
        "hi" => {},
        _ => {}, // matches have to be exhaustive 
    }
}

I also added a default case, because matches in Rust need to be exhaustive: they need to cover all possible cases.


Maybe you noticed, that I also removed the 'static from the argument list. If you want to read about some lifetime stuff, go ahead. Else, stop reading here, because it's possibly confusing and not that important in this case.

In this function there is no need to restrict the lifetime of the given argument to 'static. Maybe you also want to pass in string slices that are borrowed from a String:

let user_input = read_user_input();  // type `String`
get_project(&input);

The code above only works when you remove the 'static from the argument. Once removed, the function is equivalent to:

fn get_project<'a>(name: &'a str) { ... }

This means that the function is generic over a lifetime 'a. The function says: given any lifetime 'a, you can give me a string with said lifetime and I am able to do my thing. Which is true. If the function wouldn't be able to do it for any lifetime, the compiler would complain ;-)

Lukas Kalbertodt
  • 79,749
  • 26
  • 255
  • 305
3

In your example, name doesn't need to have a static lifetime. Because you only use name inside your function, name doesn't need to have an extended lifetime. Check out the strings chapter of The Rust Programming Language. To match a &str with a &'static str you don't need &, just the variable itself is enough.

pub fn get_project(name: &str) {
    match name {
        "hi" => println!("I found hi!"),
        _ => println!("Nothing match"),
    }
}

fn main() {
    get_project("hi");
    get_project("42");
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Stargateur
  • 24,473
  • 8
  • 65
  • 91