第二个map
此代码中的语句无法编译。
fn main() {
let hello = Some("hello");
let _switcheroo = hello.map(str::to_string); //ok
let hello = Some("hello".to_string());
let _switcheroo = hello.map(String::as_str); //not ok
}
错误是:
error[E0631]: type mismatch in function arguments
--> src/main.rs:6:29
|
6 | let _switcheroo = hello.map(String::as_str); //not ok
| ^^^
| |
| expected signature of `fn(std::string::String) -> _`
| found signature of `for<'r> fn(&'r std::string::String) -> _`
我预计会出现有关借用一些移动数据的错误。这个错误想表达什么?
这确实可以编译:
let hello = Some("hello".to_string());
let _switcheroo = hello.as_ref().map(String::as_str); //ok
最佳答案
问题是 String::as_str
期望引用 String
而不是String
本身。 String::as_str
的签名是fn as_str(&self) -> &str
,所以你可以看到需要 self
( String
)作为引用。
要解释错误消息,请查看“预期”与“发现”。在消息的“预期”部分,我们看到 fn(std::string::String) -> _
,所以它期待一个需要 std::string::String
的函数(即 String
)并返回一些不相关的类型( _
)。然而,在消息的“找到”部分,我们发现 for<'r> fn(&'r std::string::String) -> _
。这更难理解,因为它使用了 Rust 代码中很少见的想法。
for<'r>
部分意味着该函数在生命周期内应该是通用的。它应该接受任何生命周期和 String
与那一生。输出类型也可以具有给定的生命周期。通常这样的函数具有类似 fn foo(x: &T) -> &U
的签名并且生命周期是隐式添加的。这正是String::as_str
是。
修复代码的一种方法是确保将引用传递给 map
。类似 let _switcheroo = hello.as_ref().map(String::as_str);
应该可以。
关于rust - 将 String::as_str 传递给 Option<String>::map() 无法编译,并出现类型不匹配错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194680/