Advertisement
nezvers

Rust pop Cons list

Oct 4th, 2022
1,632
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.59 KB | Source Code | 0 0
  1. use crate::List::{Cons, Nil};
  2.  
  3. #[derive(Debug)]
  4. enum List {
  5.     Cons(i32, Box<List>),
  6.     Nil,
  7. }
  8.  
  9. fn main() {
  10.     let mut list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
  11.  
  12.     println!("The first value is: {}.", list.pop().unwrap());
  13.     println!("The second value is: {}.", list.pop().unwrap());
  14. }
  15.  
  16. impl List {
  17.     fn pop(&mut self) -> Option<i32> {
  18.         let old_list = (self, Nil);
  19.         match old_list {
  20.             Cons(value, tail) => {
  21.                 *self = *tail;
  22.                 Some(value)
  23.             }
  24.             Nil => None,
  25.         }
  26.     }
  27. }
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement