1

I'm trying to return a reference to a value of a newly added item to a vector in Rust. The code:

struct Element {
    id: i64,
}

struct G {
    v: Vec<Element>,
}

impl G {
    fn add(&mut self, id: i64) -> &Element {
        let new_e = Element { id };
        self.v.push(new_e);
        &self.v[self.v.len()]
    }
}

fn main() {
    let mut g = G { v: vec![] };
    let &_e1 = g.add(1);
    let &_e2 = g.add(2);
    let &_e3 = g.add(3);
}

Repl.it: https://repl.it/repls/UprightSnowSemicolon

I get the error:

error[E0507]: cannot move out of a shared reference
  --> src/main.rs:19:16
   |
19 |     let &_e1 = g.add(1);
   |         ----   ^^^^^^^^
   |         ||
   |         |data moved here
   |         |move occurs because `_e1` has type `Element`, which does not implement the `Copy` trait
   |         help: consider removing the `&`: `_e1`

And so on for _e2 and _e3.

I really want to return a reference to the newly added item inside the vector and not a copy nor an index. Is it possible?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Lucas S.
  • 312
  • 3
  • 15
  • [Remove the `&` from the variable declaration](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2b82093c0c1b81da975f68a8384e3eb9). – Shepmaster Apr 27 '20 at 14:45
  • 1
    Note that your code basically won't work. See [Cannot borrow as mutable because it is also borrowed as immutable](https://stackoverflow.com/q/47618823/155423). – Shepmaster Apr 27 '20 at 14:47

0 Answers0