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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With