How to add an element to an Option<Vec<T>>?

Hi, I have this struct with an optional vector:

pub struct Course {
    <snipped for brevity>
    pub course_participant: Option<Vec<ObjectId>>,

The problem is I cannot find the way to add a new element to that vector (with .push()). As soon as I want to work with it, I have to remove the "Option" with an unwrap(), but the unwrap() will panic if the vector is empty. Same if I want to verify first that the Vector is empty with the is_empty method, I must also unwrap first for that(egg/chicken problem?).

What would be the proper way to add an item to the Vec here?

No it won't. You seem to be confusing None with the empty vector. You might very well store an empty vector within an Option, there's nothing special about either type that would prevent you from doing so.

As for your actual problem: in order to get an associated value out of an enum, you have to match on it:

if let Some(ref mut vector) = my_option {

Based on your reply, I found my problem, which turned out to be faulty logic on my side when I created the struct. The way the struct was built, the whole field was optional(meaning that instead of having an empty vector, there was no Vector at all when I created a new course . (And indeed, looking in the database, the field is set to "null" instead of an empty array, I should have caught that earlier).

So I changed the course_participant: Option<Vec<ObjectId>>, for course_participant: Vec<Option<ObjectId>>, IT works great now. Thanks for putting me on the right path :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.