Skip to content

Instantly share code, notes, and snippets.

@kaedroho
Created March 28, 2017 12:33
Show Gist options
  • Save kaedroho/ebe30b9c01335223c8891bbd1abe80ab to your computer and use it in GitHub Desktop.
Save kaedroho/ebe30b9c01335223c8891bbd1abe80ab to your computer and use it in GitHub Desktop.
use std::fmt::Debug;
trait Atom: Debug {
fn render(&self);
}
#[derive(Debug)]
struct TextAtom {
value: String
}
impl Atom for TextAtom {
fn render(&self) {
println!("Rendering text {}", self.value);
}
}
#[derive(Debug)]
enum RenderResult {
Components(Vec<Box<Component>>),
Atom(Box<Atom>),
}
trait Component: Debug {
fn render(&self) -> RenderResult;
}
#[derive(Debug)]
struct TextComponent {
value: String,
}
impl Component for TextComponent {
fn render(&self) -> RenderResult {
RenderResult::Atom(Box::new(TextAtom {value: self.value.clone()}))
}
}
#[derive(Debug)]
struct NameComponent {
name: String,
}
impl Component for NameComponent {
fn render(&self) -> RenderResult {
RenderResult::Components(vec![
Box::new(TextComponent { value: "Hello".to_string() }),
Box::new(TextComponent { value: self.name.clone() }),
])
}
}
fn render_component(component: &Component, atoms: &mut Vec<Box<Atom>>) {
match component.render() {
RenderResult::Components(components) => {
for component in components {
render_component(&*component, atoms);
}
}
RenderResult::Atom(atom) => {
atoms.push(atom);
}
}
}
fn main() {
let component = NameComponent {
name: "Karl".to_string(),
};
let mut atoms = Vec::new();
render_component(&component, &mut atoms);
for atom in atoms {
atom.render();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment