Append Vec<T> by extend()?

Hi, I tried to append Vec by extend() but failed, any suggestion? Thanks!

struct Node {}

fn extend_nodes(other_nodes: &[Node]) {
    let mut nodes:Vec<Node> = Vec::new();
    nodes.extend(other_nodes);
}

fn main() {
    let node2:Vec<Node> = Vec::new();
    extend_nodes(node2);
}
error[E0271]: type mismatch resolving `<std::slice::Iter<'_, Node> as IntoIterator>::Item == Node`
 --> src\main.rs:5:11
  |
5 |     nodes.extend(other_nodes.iter());
  |           ^^^^^^ expected reference, found struct `Node`
  |
  = note: expected reference `&Node`
                found struct `Node`

other_nodes will produce &Node from its iterator, but extend needs owned Nodes instead. Here's a few variants that can work:

#[derive(Clone)]
struct Node;

fn extend_nodes_1(other_nodes: &[Node]) {
    let mut nodes:Vec<Node> = Vec::new();
    nodes.extend(other_nodes.into_iter().cloned());
}

fn extend_nodes_2(other_nodes: &[Node]) {
    let mut nodes:Vec<Node> = Vec::new();
    nodes.extend_from_slice(other_nodes);
}

fn extend_nodes_3(other_nodes: Vec<Node>) {
    let mut nodes:Vec<Node> = Vec::new();
    nodes.extend(other_nodes);
}

fn main() {
    let node2:Vec<Node> = Vec::new();
    extend_nodes_1(&node2);
    extend_nodes_2(&node2);
    extend_nodes_3(node2);
}
4 Likes

Thank you!

Note that Vec implements Extend<&T> if T: Clone T: Copy. So adding #[derive(Clone, Copy)] on Node will solve the issue

3 Likes

It actually wants T: Copy -- see here.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.