Created
January 7, 2016 23:22
-
-
Save anonymous/d6eee4601f927a861fb5 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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
use std::any::Any; | |
use std::rc::Rc; | |
trait AsAny { | |
fn as_any(&self) -> &Any; | |
} | |
impl<T: Any> AsAny for T { | |
fn as_any(&self) -> &Any { self } | |
} | |
type Key = usize; | |
type ChildWidgetIter<'a> = Box<Iterator<Item=(Option<Key>, Rc<Widget>)> + 'a>; | |
trait Widget: Any + AsAny { | |
fn children(&self) -> ChildWidgetIter { | |
Box::new(::std::iter::empty()) | |
} | |
fn child_count(&self) -> usize { | |
0 | |
} | |
fn allows_children(&self) -> bool { | |
false | |
} | |
fn child(&self, index: usize) -> Option<Rc<Widget>> { | |
None | |
} | |
fn insert_child(&self, index: usize, key: Option<Key>, widget: Rc<Widget>) { | |
panic!("This widget cannot be a parent.") | |
} | |
fn push_child(&self, key: Option<Key>, widget: Rc<Widget>) { | |
panic!("This widget cannot be a parent.") | |
} | |
fn remove_child(&self, index: usize) { | |
panic!("This widget has no children.") | |
} | |
} | |
impl Widget { | |
fn downcast_ref<T: Widget>(&self) -> Option<&T> { | |
self.as_any().downcast_ref::<T>() | |
} | |
} | |
struct Foo; | |
impl Widget for Foo { | |
} | |
fn main() { | |
let x: Rc<Widget> = Rc::new(Foo); | |
for child in x.children() { | |
} | |
//let x: &Foo = x.downcast_ref().unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment