Created
February 10, 2015 10:29
-
-
Save drewcrawford/d699688f6d02deeed979 to your computer and use it in GitHub Desktop.
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
/** An example statically-dispatched, trait-based recursive datastructure in Rust */ | |
/**A master trait */ | |
trait Link { | |
fn value(&self) -> i32; | |
fn next(&self) -> Option<&Link>; | |
fn sumOfValue(&self)->i32 { | |
let maybeNext = self.next(); | |
match maybeNext { | |
Some(v) => { | |
return self.value() + v.sumOfValue() | |
} | |
None => { | |
return self.value() | |
} | |
} | |
} | |
} | |
/**A specialization of Link with value = 1 */ | |
struct OneLink<NEXT: Link> { | |
next : NEXT | |
} | |
impl<NEXT : Link> Link for OneLink<NEXT> { | |
fn value(&self) -> i32 { 1 } | |
fn next(&self) -> Option<&Link> { Some(&self.next) } | |
} | |
/**another specialization of link with value = 2*/ | |
struct TwoLink<NEXT: Link> { | |
next: NEXT | |
} | |
impl<NEXT : Link> Link for TwoLink<NEXT> { | |
fn value(&self) -> i32 { 2 } | |
fn next(&self) -> Option<&Link> { Some(&self.next) } | |
} | |
/**Another specialization of link with value 0 and no next element */ | |
struct NoLink; | |
impl Link for NoLink { | |
fn value(&self) -> i32 { 0 } | |
fn next(&self) -> Option<&Link> { None } | |
} | |
fn main() { | |
/**A chain of One -> Two -> None, for a total value of 3*/ | |
let chain = OneLink{ next: TwoLink { next: NoLink } }; | |
/**Calculate the total value */ | |
println!("{}",chain.sumOfValue()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment