简体   繁体   中英

How to match against a &'static str in Rust

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`

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 ;-)

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM