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?