0

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.

  • 2
    You should avoid creating such structures, once the structure references itself, you won't be able to mutate `all_things` or even move `my_backpack`, which can be quite limiting. See the link for more info and alternatives, the most common with referencing vecs is to move to an index-based strategy. – kmdreko Oct 05 '21 at 06:24
  • 1
    Do you really need to distinguish an empty backpack (`Some(vec![])`) from an absence of backpack (`None`)? You could probably simplify your code by declaring `all_things` as a simple `Vec` without the `Option`. – Jmb Oct 05 '21 at 06:35

1 Answers1

0

When you do my_backpack.all_things.unwrap(), you take the ownership of the value in the Option enum, thus the borrow checker error.

All you need to do is to reference the vector instead of taking the ownership:

my_backpack.favorite = Some([
        &my_backpack.all_things.as_ref().unwrap()[0],
        &my_backpack.all_things.as_ref().unwrap()[1],
]);
Maxim Gritsenko
  • 2,396
  • 11
  • 25