2

I have a struct container of Children and a method pop() that removes the last added Child and returns it's a value:

struct Child {
    a: i32,
    b: String,
}

struct Container<'a> {
    vector: &'a mut Vec<Child>,
}

impl<'a> Container<'a> {
    fn pop(&mut self) -> i32 {
        return self.vector.pop().a;
    }
}

I get the error during compilation:

error: no field `a` on type `std::option::Option<Child>`
  --> src/main.rs:12:34
   |
12 |         return self.vector.pop().a;
   |                                  ^

Does the scope of Container's pop() not allow access to values of its Children's scope?

1 Answer 1

8

Vec::pop returns an Option<Child>, not a Child. This allows it to have something reasonable to return in case there are no elements in the Vec to pop off. To get at the a that may be inside, you can convert from Option<Child> to Child using unwrap(), but that will cause your program to panic if the Vec was empty. The code for that would look like this:

fn pop(&mut self) -> i32 {
    return self.vector.pop().unwrap().a;
}

Another option would be to more closely copy Vec's behavior, and return None in case there are no elements. You could do that using Option's map method:

fn pop(&mut self) -> Option<i32> {
    return self.vector.pop().map(|child| child.a)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great, I didn't pay attention to the Option type, I've just started playing with Rust. It's pretty cool! Thx.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.