小编Har*_*751的帖子

为什么我无法从对带有 String 的结构体的引用的迭代器中收集 Vec<&str> ?

我目前正在学习 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

5
推荐指数
1
解决办法
101
查看次数

标签 统计

rust ×1