Skip to content

Instantly share code, notes, and snippets.

@whatisaphone
Created May 16, 2014 16:48
Show Gist options
  • Save whatisaphone/44ff6b0006cd441c0e19 to your computer and use it in GitHub Desktop.
Save whatisaphone/44ff6b0006cd441c0e19 to your computer and use it in GitHub Desktop.
Rust example of overloading using enums
trait Node { }
struct LI {
nodes: Vec<Box<Node>>
}
impl Node for LI { }
struct A<'a> {
nodes: Vec<Box<Node>>,
href: &'a str,
}
impl<'a> Node for A<'a> { }
struct TextNode<'a> {
content: &'a str
}
impl<'a> Node for TextNode<'a> { }
enum ElementContent<'a> {
NodeContent(Box<Node>),
StrContent(&'a str),
}
fn gimme_a_nodelist(content: ElementContent) -> Vec<Box<Node>> {
match content {
NodeContent(node) => vec!(node),
StrContent(text) => vec!(box TextNode { content: text } as Box<Node>),
}
}
fn li(content: ElementContent) -> LI {
LI { nodes: gimme_a_nodelist(content) }
}
fn a<'a>(content: ElementContent, href: &'a str) -> A<'a> {
A { nodes: gimme_a_nodelist(content), href: href }
}
fn main() {
let item1 = li(StrContent("not a link"));
let item2 = li(NodeContent(box a(StrContent("link"), "http://www.rust-lang.org/")));
//let item1 = li("not a link");
//let item2 = li(box a("link", "http://www.rust-lang.org/"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment