Skip to content

Instantly share code, notes, and snippets.

@drewcrawford
Created February 10, 2015 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drewcrawford/d699688f6d02deeed979 to your computer and use it in GitHub Desktop.
Save drewcrawford/d699688f6d02deeed979 to your computer and use it in GitHub Desktop.
/** 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