访问 Vec 或切片的最后一个元素 [英] Accessing the last element of a Vec or a slice

查看:30
本文介绍了访问 Vec 或切片的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的代码:

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"),
    }
}

现在,top() 方法正在修改self,但我认为这应该没有必要.显而易见的方法并没有真正奏效:

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],
    }
}

我曾尝试将 usize 转换为 i32 并返回,但我写的所有内容都没有我认为的那么简短易读.

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.

推荐答案

在发布问题后,答案似乎很明显:

And just after posting the question, the answer appears to be obvious:

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

usize 从来都不是问题 - top() 的返回类型是.

I.e. the usize was never the problem - the return type of top() was.

这篇关于访问 Vec 或切片的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆