0

Why does the following rust code work?

fn main() {
    let a = Some(vec![1, 2, 3]);

    let b = &a.unwrap(); // .unwrap() takes ownership of the Option<Vec<i32>>

    dbg!(b); // Why can I do this? a is no longer the owner of Some(vec![1, 2, 3]), and should've been dropped.
    // Who owns Some(vec![1, 2, 3])?
}
Antosser
  • 346
  • 1
  • 9
  • I don't understand your issue, you're using `b`, that take the value inside `a`. Even `a` is not longer accessible as the value is moved, you can still access the moved value on `b`. – Mario Santini Aug 18 '23 at 09:24
  • @MarioSantini But b doesn't own the Vec, only the reference to it – Antosser Aug 18 '23 at 09:26
  • No, the value it's moved, so the vec now is owned by b. – Mario Santini Aug 18 '23 at 09:27
  • @MarioSantini No, `b` is a reference. A reference borrows a value, it does not own it. – Sven Marnach Aug 18 '23 at 11:09
  • Sorry, my sentence: "the vec is owned by b" is wrong, but it does not change the result, as the value unwrapped should live long enought to be a valid reference until the main function exits. – Mario Santini Aug 18 '23 at 12:13

0 Answers0