我正在尝试将给定结构的Vec
转换为其String
并最终转换为&str
格式。
此示例代码完全模拟了我要实现的目标。
fn main() {
let a = vec![1i32, 2i32, 3i32];
let step1: Vec<String> = a.iter().map(|x| x.to_string()).collect::<Vec<String>>();
let step2: Vec<&str> = step1.iter().map(AsRef::as_ref).collect::<Vec<&str>>();
// This does not work as I was expecting it to
// and its not being accepted by the compiler as valid code
//
let in_single_step: Vec<&str> = a
.iter()
.map(|x| x.to_string()) // <--- Something is needed after this step?
.map(AsRef::as_ref)
.collect::<Vec<&str>>();
println!("{:?}", in_single_step);
}
我得到一个错误:
error[E0631]: type mismatch in function arguments
--> src/main.rs:14:10
|
14 | .map(AsRef::as_ref)
| ^^^
| |
| expected signature of `fn(std::string::String) -> _`
| found signature of `for<'r> fn(&'r _) -> _`
error[E0599]: no method named `collect` found for type `std::iter::Map<std::iter::Map<std::slice::Iter<'_, i32>, [closure@src/main.rs:13:14: 13:31]>, for<'r> fn(&'r _) -> &'r _ {<_ as std::convert::AsRef<_>>::as_ref}>` in the current scope
--> src/main.rs:15:10
|
15 | .collect::<Vec<&str>>();
| ^^^^^^^
|
= note: the method `collect` exists but the following trait bounds were not satisfied:
`&mut std::iter::Map<std::iter::Map<std::slice::Iter<'_, i32>, [closure@src/main.rs:13:14: 13:31]>, for<'r> fn(&'r _) -> &'r _ {<_ as std::convert::AsRef<_>>::as_ref}> : std::iter::Iterator`
`std::iter::Map<std::iter::Map<std::slice::Iter<'_, i32>, [closure@src/main.rs:13:14: 13:31]>, for<'r> fn(&'r _) -> &'r _ {<_ as std::convert::AsRef<_>>::as_ref}> : std::iter::Iterator`
类似的问题是: