title: Accessing the last element of a Vec or a slice
body: <p>I have some code that looks like this:</p>
  
  <pre><code>trait Stack {
      fn top(&amp;mut self) -&gt; Option&lt;f64&gt;;
  }
  
  impl Stack for Vec&lt;f64&gt; {
      fn top(&amp;mut self) -&gt; Option&lt;f64&gt; {
          match self.pop() {
              None =&gt; None,
              Some(v) =&gt; {
                  self.push(v);
                  Some(v)
              }
          }
      }
  }
  
  fn main() {
      let mut stack: Vec&lt;f64&gt; = Vec::new();
      stack.push(5.3);
      stack.push(2.3);
      stack.push(1.3);
  
      match stack.top() {
          Some(v) =&gt; println!("Top of the stack: {}", v),
          None =&gt; println!("The stack is empty"),
      }
  }
  </code></pre>
  
  <p>Right now, the <code>top()</code> method is modifying <code>self</code>, but I think that this should not be necessary. The obvious way to do it didn't really work:</p>
  
  <pre><code>fn top(&amp;mut self) -&gt; Option&lt;f64&gt; {
      match self.len() {
          0 =&gt; None,
          n =&gt; self[n - 1],
      }
  }
  </code></pre>
  
  <p>I've toyed around a bit with converting <code>usize</code> to <code>i32</code> and back, but none of what I'm writing looks as short and readable as I think it should.</p>