imagine you have this two structs, one for creating things and one to store them.
struct Things {
name: String,
}
struct Backpack<'backpack> {
all_things: Option<Vec<Things>>,
favorite: Option<[&'backpack Things; 2]>,
}
all_things in Backpack are all the things that you are carrying around, but you can choose only two to be your favorite things.
in orther to add things to your backpack you run this code
let thing1 = Things {
name: String::from("pencil"),
};
let thing2 = Things {
name: String::from("notebook"),
};
let thing3 = Things {
name: String::from("phone"),
};
let mut my_backpack = Backpack {
all_things: None,
favorite: None,
};
my_backpack.all_things = Some(vec![thing1, thing2, thing3]);
you first initialize your backpack to be empty, and then add some items to your backpack.
The problem I have is to add items to favorite, because I only want a reference to that item from all_things.
my_backpack.favorite = Some([
&my_backpack.all_things.unwrap()[0],
&my_backpack.all_things.unwrap()[1],
])
whenever I do this, I got a compile error saying that the value has being moved. How can I create an array of my favorite things with only references from all_things that are in my backpack. I don't want to copy them because they already exists on all_things.
Note that all_things and favorite can be empty, so that's why I use Option enum.