Error "the type of this value must be known in this context" according to the pattern

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 get 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 str type is &str from the function definition? What am I missing here?

+5
source share
1 answer

The location of the error can be confusing, the problem here is in the collect method. It is common to any FromIterator , in which case the compilerโ€™s cat prints the type (which compiler sees, you need some type X that implements FromIterator , which has the as_slice method that creates & str).

The second problem with this code is that you are trying to return a link to a local value (the result of the collection) from the matching operator. You cannot do this because this value has the lifetime of this block and is freed after that, so the returned one will 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 at the end, but look at MaybeOwned if this is a function that returns a slice ( &str ) or String .

+4
source

Source: https://habr.com/ru/post/1202474/


All Articles