Getting the last element out of Option<Vec<i32>>

After defining a struct like so:

pub struct Vers {
        pub bk: String,
        pub ch: u32,
        pub vs: u32,
        pub a: Option<Vec<i32>>,
        pub b: Option<Vec<i32>>,
    }

And creating an instance like so:

let v1 = Vers {
        bk: String::from("Canticum"),
        ch: 1,
        vs: 1,
        a: Some(vec![71, 73, 71, 00]),
        b: None,
    };

I need a function to extract the last, or first element of the vector, without taking ownership.

I started with the one below, but this, of course, takes ownership. And, probably, it can be done more effectively. So any help is welcome.

fn last_acc(v: Option<Vec<i32>>) {
        let vs = v.unwrap();
        let lst = vs.last();
        println!("{:?}", lst.unwrap());
    }

I don't see how your last_acc corresponds to getting an element, or know which of your two vectors you're trying to get something out of, so I'll just answer:

How can one get or extract the last element of an Option<Vec<i32>> field without taking ownership?

You can use as_ref and as_mut to get Option<& [mut] Vec<_>>s, and then use and_then to perform Option-returning operations on the Vec reference.

    fn last(&self) -> Option<i32> {
        self.v.as_ref().and_then(|v| v.last().copied())
    }
    fn pop(&mut self) -> Option<i32> {
        self.v.as_mut().and_then(|v| v.pop())
    }

Playground.

3 Likes