Skip to content

Instantly share code, notes, and snippets.

@pythonesque
Created March 10, 2015 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pythonesque/d6409604cfb835b8833d to your computer and use it in GitHub Desktop.
Save pythonesque/d6409604cfb835b8833d to your computer and use it in GitHub Desktop.
#![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();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment