Skip to content

Instantly share code, notes, and snippets.

@dns2utf8
Last active November 1, 2019 22:30
Show Gist options
  • Save dns2utf8/6550ff8ff35205bc718ea8ca4f8b6217 to your computer and use it in GitHub Desktop.
Save dns2utf8/6550ff8ff35205bc718ea8ca4f8b6217 to your computer and use it in GitHub Desktop.
// Source: https://gist.github.com/dns2utf8/6550ff8ff35205bc718ea8ca4f8b6217
use core::ops::{Deref, DerefMut};
use std::any::Any;
#[derive(Default, Clone, Debug)]
pub struct Part {
pub count: u16,
}
#[derive(Default, Clone, Debug)]
pub struct Apartments {
pub content: Part,
pub number: u16,
}
impl Deref for Apartments {
type Target = Part;
fn deref(&self) -> &Self::Target {
&self.content
}
}
impl DerefMut for Apartments {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.content
}
}
#[derive(Default, Clone, Debug)]
pub struct Roads {
pub content: Part,
pub length: u16,
}
impl Deref for Roads {
type Target = Part;
fn deref(&self) -> &Self::Target {
&self.content
}
}
trait ComponentPart {
fn part(&self) -> &Part;
fn as_any(&self) -> &dyn Any;
}
impl ComponentPart for Apartments {
fn part(&self) -> &Part {
&self.content
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl ComponentPart for Roads {
fn part(&self) -> &Part {
&self.content
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn main() {
let mut a: Apartments = Default::default();
let r: Roads = Default::default();
a.count += 5;
assert_eq!(2 + 3, a.count + r.count);
// Liste mit VTable
let l: Vec<Box<dyn ComponentPart>> = vec![Box::new(a), Box::new(r)];
for (i, p) in l.iter().enumerate() {
let debug_string = get_debug_string(p.as_any());
println!("{}: {:?} => {}", i, p.part(), debug_string);
}
}
fn get_debug_string(value: &dyn Any) -> String {
match (value.downcast_ref::<Apartments>(), value.downcast_ref::<Roads>()) {
(Some(a), _) => format!("{:?}", a),
(_, Some(r)) => format!("{:?}", r),
e => format!("Unknown Type: {:?}", e),
}
}
@dns2utf8
Copy link
Author

dns2utf8 commented Nov 1, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment