Vector 访问Vec或切片的最后一个元素
我有一些代码如下所示:Vector 访问Vec或切片的最后一个元素,vector,rust,Vector,Rust,我有一些代码如下所示: 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) => {
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"),
}
}
我曾经尝试过将
usize
转换成i32
再转换回来,但我所写的内容都没有我想象的那么简短易读。发布问题后,答案似乎很明显:
fn top (&mut self) -> Option<&f64> {
match self.len() {
0 => None,
n => Some(&self[n-1])
}
}
fn-top(&mut-self)->选项{
匹配self.len(){
0=>无,
n=>Some(&self[n-1])
}
}
也就是说,usize
从来都不是问题-返回类型为top()
。您可以使用:
fn-top(&mut-self)->选项{
self.last().copied()
}
(和)可用于从选项
转换为选项
,匹配所需的功能签名
您还可以从实现和特征定义中删除
mut
。f64
是Copy
,因此返回类型中的&
和匹配的臂也不是必需的。
fn top (&mut self) -> Option<&f64> {
match self.len() {
0 => None,
n => Some(&self[n-1])
}
}
fn top(&mut self) -> Option<f64> {
self.last().copied()
}