Djent
Djent

Reputation: 3467

Cannot get owned object by cloning it

I have a reference to a vector of structs. I want to create a reference of an enumerated vector with given structs (but not struct references). I do a clone() to obtain the new instances but it doesn't seem to work. Here's a simplified version of my code:

struct Item {
    name: String,
}

fn get_enumerated(data: &Vec<Item>) -> Vec<(usize, Item)> {
    data.iter()
        .enumerate()
        .map(|(i, item)| (i, item.clone()))
        .collect()
}

The error I get is:

error[E0277]: a value of type `Vec<(usize, Item)>` cannot be built from an iterator over elements of type `(usize, &Item)`
 --> src/lib.rs:9:10
  |
9 |         .collect()
  |          ^^^^^^^ value of type `Vec<(usize, Item)>` cannot be built from `std::iter::Iterator<Item=(usize, &Item)>`
  |
  = help: the trait `FromIterator<(usize, &Item)>` is not implemented for `Vec<(usize, Item)>`

It doesn't matter how many clones I'll put there, even if I'll duplicate the line with map() multiple times, it's still a reference.

Why the clone() doesn't work here? And how do I change the reference to an owned object here?

Upvotes: 2

Views: 208

Answers (1)

Netwave
Netwave

Reputation: 42708

You are missing the clone derive on your struct, so it is just cloning the reference to it:

#[derive(Clone)]
struct Item {
    name: String,
}

Playground

Upvotes: 3

Related Questions