Last active
December 25, 2015 17:49
-
-
Save JeffBelgum/7016255 to your computer and use it in GitHub Desktop.
Linked List push function
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
#[deriving(ToStr, Clone, Eq)] | |
enum List<T> { | |
Cons(T, @mut List<T>), | |
Nil | |
} | |
/* | |
* from brson: it could be more efficient by avoiding that clone, | |
* since the cost of cloning a T could be arbitrary. | |
* | |
* with that signature, one thing you could do is swap Nil into l, | |
* then assign the new Cons to l without cloning the original l | |
* | |
* from bdaupp: it's hard to avoid both the infinite loop and the .clone with | |
* that design (i.e using @mut), personally I'd take either &mut @mut List, or | |
* return a new @mut List with the body being @mut Cons(v, l) | |
* | |
*/ | |
pub fn push<T: 'static + Clone>(l: &mut List<T>, v: T) { | |
*l = Cons(v, @mut((*l).clone())); | |
} | |
/* | |
pub fn pop<T: Clone>(l: &mut List<T>) -> T { | |
*l = | |
} | |
*/ | |
fn main() { | |
let list = @mut Cons(1i, @mut Nil); | |
push(list, 2i); | |
push(list, 3i); | |
println(list.to_str()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment