请考虑以下示例
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);
}
Run Code Online (Sandbox Code Playgroud)
我收到了这个错误
error: the type of this value must be known in this conntext
true => str.chars().map(|x| x.to_lowercase()).collect().as_slice()
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我有点困惑,编译器是否知道类型str是&str来自函数定义?我在这里错过了什么?
错误位置可能令人困惑,这里的问题是collect方法。它对于任何类型都是通用的FromIterator,在这种情况下,编译器会推断类型(编译器看到的是您需要某种类型 X 实现FromIterator,该实现as_slice具有生成 &str 的方法)。
此代码的第二个问题是您尝试从 match 语句返回对本地值(收集的结果)的引用。您不能这样做,因为该值具有该块的生命周期并在之后被释放,因此返回的值将无效。
一种可行的解决方案(但需要将 &str 转换为字符串):
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);
}
Run Code Online (Sandbox Code Playgroud)
我不知道你最终想要实现什么,但看看MaybeOwned这是否是一个返回 slice ( &str) 或String.