RUST Unwrap() - Understanding

Hi,
Can anyone clarify this statement, from the docs, about unwrap() on Options:

Returns the contained [Some] value, consuming the self value.

What does 'consume' means in this line and context. I thought probably the variable containing the option is invalidated after the call but it doesnt seem so.
So e.g.

pub fn main() {
    let f = Some(1);
    // So I though f's finished after this following call
    // Consumed
    let g = f.unwrap();
    println!("value of g:{}", g);
    // But I can call it again, so what does consume mean?
    let m = f.unwrap();
    println!("Value of m:{}", m)
}

Thanks,

When the type is Copy, the option is not destroyed. I suggest you try again with your example modified to use a non-Copy type. Then you should get the expected behavior.

6 Likes

aah yea that's correct..The compiler gave me the stick with a non copy type..

Cheers,

In general when learning, I suggest using String or some other non-Copy type as your go-to dummy type (versus an integer or something), as situations like this come up somewhat frequently.

4 Likes