I want to learn the ownership model of Rust. In the example below I want to spawn
a NonCopy
object child
from the existing NonCopy
object eva
and save them in the same vector population
.
#[derive(Debug, PartialEq, Hash)]
pub struct NonCopy<'a> {
name: String,
parent: Option<&'a NonCopy<'a>>,
}
impl<'a> NonCopy<'a> {
pub fn new(name: String, parent: Option<&'a NonCopy<'a>>) -> Self { // we create a method to instantiate `NonCopy`
NonCopy { name: name, parent: parent }
}
pub fn say_name(&self) -> String {
format!("{:}", self.name)
}
}
pub fn spawn<'a>(parent: &'a NonCopy, name: String) -> NonCopy<'a> {
NonCopy::new(name, Some(parent))
}
fn main() {
let eva = NonCopy::new(String::from("Eva"), None);
let child = spawn(&eva, String::from("Son"));
let mut population = vec![child];
population.push(eva);
}
But when I push eva
to the vector object population
I get following error message:
Compiling playground v0.1.0 (/home/holger/git/Rust/playground)
error[E0505]: cannot move out of `eva` because it is borrowed
--> src/main.rs:25:21
|
23 | let child = spawn(&eva, String::from("Son"));
| ---- borrow of `eva` occurs here
24 | let mut population = vec![child];
25 | population.push(eva);
| ---- ^^^ move out of `eva` occurs here
| |
| borrow later used by call
error: aborting due to previous error
For more information about this error, try `rustc --explain E0505`.
error: could not compile `playground`.
I would like to ask why it is not possible to push
eva
to the same vector as its spawned child child
.
eva
is borrowd to the functionspawn
. According to Rust By Example the borrow should be dropped after the end ofspawn
. Why isn't it dropped?- Is it because the result of
spawn
is still alive after the end ofspawn
? - Is this behaviour related to its non
Copy
type? - How can
eva
andchild
be collected in the sameVec
object?