Created
April 11, 2020 21:49
-
-
Save wdevore/a5b1fad7eff708bbc955b1017854b11e to your computer and use it in GitHub Desktop.
Simple Rust stack using Copy and Clone
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug, Copy, Clone)] | |
pub struct Thing { | |
value: f64, | |
} | |
struct Node { | |
val: Thing, | |
next: Option<Box<Node>>, | |
} | |
pub struct Stack { | |
top: Option<Box<Node>>, | |
} | |
impl Stack { | |
pub fn new() -> Stack { | |
Stack { | |
top: None, | |
} | |
} | |
pub fn push(&mut self, val: Thing) { | |
self.top = Some(Box::new(Node { | |
val: val, | |
next: self.top.take(), | |
})) | |
} | |
pub fn pop(&mut self) { | |
match self.top.take() { | |
None => return, | |
Some(mut node_box) => self.top = (*node_box).next.take(), | |
} | |
} | |
pub fn top(&self) -> &Thing { | |
match &self.top { | |
&None => panic!(), | |
&Some(ref node_box) => &(*node_box).val, | |
} | |
} | |
} | |
fn show(t: &mut Thing) { | |
t.value += 2.0; | |
println!("show: {:?}", t); | |
} | |
fn main() { | |
let mut st = Stack{top: None}; | |
let mut y = Thing { value: 5.0 }; | |
st.push(y); | |
show(&mut y); | |
println!("{:?}", y); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment