Skip to content

Instantly share code, notes, and snippets.

@zesterer
Last active August 7, 2018 12:26
Show Gist options
  • Save zesterer/be2629fc8c8f596ff971f71b68bf5d0b to your computer and use it in GitHub Desktop.
Save zesterer/be2629fc8c8f596ff971f71b68bf5d0b to your computer and use it in GitHub Desktop.
Example Rust widget library design
use std::cell::RefCell;
use std::rc::Rc;
trait Widget {
fn add(&self, w: Rc<Widget>) -> Rc<Widget> { w }
fn children(&self) -> Vec<Rc<Widget>> { vec!() }
fn type_name(&self) -> &'static str;
fn print_tree(&self, depth: i32) {
for _ in 0..depth { print!(" "); }
println!("{}", self.type_name());
for c in self.children() { c.print_tree(depth + 1); }
}
}
// Button
struct Button;
impl Button {
fn new() -> Rc<Button> { Rc::new(Button) }
}
impl Widget for Button {
fn type_name(&self) -> &'static str { "Button" }
}
// HBox
struct HBox {
children: RefCell<Vec<Rc<Widget>>>,
}
impl HBox {
fn new() -> Rc<HBox> { Rc::new(HBox { children: RefCell::new(vec!()) }) }
}
impl Widget for HBox {
fn add(&self, w: Rc<Widget>) -> Rc<Widget> { self.children.borrow_mut().push(w.clone()); w }
fn children(&self) -> Vec<Rc<Widget>> { self.children.borrow_mut().clone() }
fn type_name(&self) -> &'static str { "HBox" }
}
// An example widget hierarchy
fn main() {
let mut hbox = HBox::new();
hbox.add(Button::new());
let mut hbox2 = hbox.add(HBox::new());
hbox2.add(Button::new());
hbox.print_tree(0);
// Prints:
//
// HBox
// Button
// HBox
// Button
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment