Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error "type of this value must be known in this context" in pattern matching

Tags:

rust

Consider the following example

fn main () {
    f("hello", true);
}

fn f(str: &str, sen: bool) {
    let s: &str = match sen {
        false => str,
        true => str.chars().map(|x| x.to_lowercase()).collect().as_slice()
    };
    println!("{}", s);
}

I'm getting this error

error: the type of this value must be known in this conntext                                                                                                                                                              
true => str.chars().map(|x| x.to_lowercase()).collect().as_slice()
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I'm a bit confused, doesn't the compiler know that the type of str is &str from the function definition? What am I missing here?

like image 544
Jacob Wang Avatar asked Sep 30 '22 21:09

Jacob Wang


1 Answers

The error location is maybe confusing, the problem here is the collect method. It is generic for any FromIterator and in this case the compiler cat infer the type (what compiler sees is you need some type X implementing FromIterator that has an as_slice method producing a &str).

The second problem with this code that you are trying to return a reference to a local value (result of collect) from the match statement. You can't do that because that value has the lifetime of that block and is deallocated after, so the returned would be invalid.

One working solution (but it requires converting &str to String):

fn main () {
    f("hello", true);
}

fn f(str: &str, sen: bool) {
    let s: String = match sen {
        false => str.to_string(),
        true => str.chars().map(|x| x.to_lowercase()).collect()
    };
    println!("{}", s);
}

I don't know what you are trying to achieve in the end but take a look at MaybeOwned if this will be a function returning a slice (&str) or a String.

like image 80
Arjan Avatar answered Oct 05 '22 08:10

Arjan