patternrustModerate
Accessing the last element of a Vec or a slice
Viewed 0 times
lastslicetheaccessingelementvec
Problem
I have some code that looks like this:
Right now, the
I've toyed around a bit with converting
trait Stack {
fn top(&mut self) -> Option;
}
impl Stack for Vec {
fn top(&mut self) -> Option {
match self.pop() {
None => None,
Some(v) => {
self.push(v);
Some(v)
}
}
}
}
fn main() {
let mut stack: Vec = 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 {
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.Solution
And just after posting the question, the answer appears to be obvious:
I.e. the
fn top (&mut self) -> Option {
match self.len() {
0 => None,
n => Some(&self[n-1])
}
}I.e. the
usize was never the problem - the return type of top() was.Code Snippets
fn top (&mut self) -> Option<&f64> {
match self.len() {
0 => None,
n => Some(&self[n-1])
}
}Context
Stack Overflow Q#28280035, score: 28
Revisions (0)
No revisions yet.