Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

vector - Accessing the last element of a Vec or a slice

I have some code that looks like this:

trait Stack {
    fn top(&mut self) -> Option<f64>;
}

impl Stack for Vec<f64> {
    fn top(&mut self) -> Option<f64> {
        match self.pop() {
            None => None,
            Some(v) => {
                self.push(v);
                Some(v)
            }
        }
    }
}

fn main() {
    let mut stack: Vec<f64> = Vec::new();
    stack.push(5.3);
    stack.push(2.3);
    stack.push(1.3);

    match stack.top() {
        Some(v) => println!("Top of the stack: {}", v),
        None => println!("The stack is empty"),
    }
}

Right now, the top() method is modifying self, but I think that this should not be necessary. The obvious way to do it didn't really work:

fn top(&mut self) -> Option<f64> {
    match self.len() {
        0 => None,
        n => self[n - 1],
    }
}

I've toyed around a bit with converting usize to i32 and back, but none of what I'm writing looks as short and readable as I think it should.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use slice::last:

fn top(&mut self) -> Option<f64> {
    self.last().copied()
}

Option::copied (and Option::cloned) can be used to convert from an Option<&f64> to an Option<f64>, matching the desired function signature.

You can also remove the mut from both the implementation and the trait definition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...