我目前正在学习 Rust,我想从拥有字符串的项目向量中收集字符串 (&strs) 的引用。
struct Channel {
cid: usize,
name: String,
}
fn main() {
let channels: Vec<Channel> = vec![Channel {
cid: 1,
name: "Hello".to_string(),
}];
let names: Vec<&str> = channels.iter().map(|x| &x.name).collect();
}
Run Code Online (Sandbox Code Playgroud)
此代码无法编译,出现以下错误:
[E0277]: a value of type `Vec<&str>` cannot be built from an iterator over elements of type `&String`
--> src/main.rs:11:61
|
11 | let names: Vec<&str> = channels.iter().map(|x| &x.name).collect();
| ^^^^^^^ value of type `Vec<&str>` cannot be built from `std::iter::Iterator<Item=&String>`
|
= help: the trait `FromIterator<&String>` is …Run Code Online (Sandbox Code Playgroud) rust ×1