Skip to content

Instantly share code, notes, and snippets.

@pythonesque
Created March 10, 2015 21:39

Revisions

  1. pythonesque created this gist Mar 10, 2015.
    62 changes: 62 additions & 0 deletions inheritance.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    #![feature(core)]

    macro_rules! inherit {
    {
    $(#[$flag_struct:meta])* struct $child:ident : $parent:ty {
    $($(#[$flag_field:meta])* $field:ident: $ty:ty),*
    }
    } => {
    extern crate core;

    $(#[$flag_struct])* struct $child {
    super_: $parent,
    $($(#[$flag_field])* $field: $ty),*
    }

    impl core::ops::Deref for $child {
    type Target = $parent;

    fn deref(&self) -> &$parent { &self.super_ }
    }

    impl core::ops::DerefMut for $child {
    fn deref_mut(&mut self) -> &mut $parent { &mut self.super_ }
    }
    }
    }

    struct Parent { parent_member: &'static str }

    trait SomeTrait {
    fn overriden_method(&self);
    }

    impl Parent {
    fn super_method(&self) {
    println!("I am in the parent: {} and will not be overriden in the child.", self.parent_member);
    }
    }

    impl SomeTrait for Parent {
    fn overriden_method(&self) {
    println!("I am in the parent: {} but will be overriden in the child.", self.parent_member);
    }
    }

    inherit! {
    struct Child : Parent { child_member: &'static str }
    }

    impl SomeTrait for Child {
    fn overriden_method(&self) {
    println!("I am in the child: {} and will call explicit super on my parent.", self.child_member);
    self.super_.overriden_method();
    }
    }

    fn main() {
    let child = Child { super_: Parent { parent_member: "Parent" }, child_member: "Child" };

    child.super_method();
    child.overriden_method();
    }