Last active
August 29, 2015 14:12
-
-
Save MarkJr94/9b2867c17f9ca60f1bbe to your computer and use it in GitHub Desktop.
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
#![feature(macro_rules)] | |
use std::ops::{Deref, DerefMut}; | |
macro_rules! extend { | |
(struct $name:ident extends $parent:ident { | |
$($field:ident: $typ_:ty),+ | |
}) => ( | |
struct $name { | |
__super: $parent, | |
$($field: $typ_),+ | |
} | |
impl Deref<$parent> for $name { | |
fn deref<'a>(&'a self) -> &'a $parent { | |
&self.__super | |
} | |
} | |
impl DerefMut<$parent> for $name { | |
fn deref_mut<'a>(&'a mut self) -> &'a mut $parent { | |
&mut self.__super | |
} | |
} | |
) | |
} | |
struct Dummy<R> { | |
data: R | |
} | |
impl<R> Dummy<R> { | |
fn new(r: R) -> Dummy<R> { | |
Dummy { data: r} | |
} | |
} | |
impl<R> Deref<R> for Dummy<R> { | |
fn deref<'a>(&'a self) -> &'a R { | |
&self.data | |
} | |
} | |
impl<R> DerefMut<R> for Dummy<R> { | |
fn deref_mut<'a>(&'a mut self) -> &'a mut R { | |
&mut self.data | |
} | |
} | |
struct Point { | |
pub x: int, | |
pub y: int, | |
} | |
impl Point { | |
fn new(x: int, y: int) -> Point { | |
Point { | |
x: x, | |
y: y | |
} | |
} | |
fn tup(&self) -> (int, int) { | |
(self.x, self.y) | |
} | |
fn product(&self) -> int { | |
self.x * self.y | |
} | |
} | |
struct VecExt<T> { | |
v: Vec<T> | |
} | |
impl<T> VecExt<T> { | |
fn new (v: Vec<T>) -> VecExt<T> { | |
VecExt { v: v} | |
} | |
fn len(&self) -> uint { self.v.len() + 1 } | |
} | |
impl<T> Deref<Vec<T>> for VecExt<T> { | |
fn deref<'a>(&'a self) -> &'a Vec<T> { | |
&self.v | |
} | |
} | |
impl<T> DerefMut<Vec<T>> for VecExt<T> { | |
fn deref_mut<'a>(&'a mut self) -> &'a mut Vec<T> { | |
&mut self.v | |
} | |
} | |
extend!{struct Point3 extends Point { | |
z: int | |
}} | |
impl Point3 { | |
fn new(x: int, y: int, z:int) -> Point3 { | |
Point3 { | |
__super: Point::new(x, y), | |
z: z | |
} | |
} | |
fn tup3(&self) -> (int, int, int) { | |
(self.x, self.y, self.z) | |
} | |
fn product(&self) -> int { | |
self.x * self.y * self.z | |
} | |
} | |
fn main() { | |
use std::io::stdin; | |
let mut d = Dummy::new(stdin()); | |
let input = d.read_to_end(); | |
println!("{}", input); | |
let p = Dummy::new(Point::new(1,2)); | |
println!("(*p).x {}", (*p).x); | |
println!("p.x {}", p.x); | |
assert!(p.x == (*p).x); | |
let mut v = VecExt::new(vec![1i,2,3,4]); | |
v.push(5); | |
println!("v.len(): {}", v.len()); | |
let p3 = Point3::new(1,2,3); | |
println!("p3.tup(): {}", p3.tup()); | |
println!("p3.tup3(): {}", p3.tup3()); | |
println!("x = {}, y = {}, z = {}", p3.x, p3.y, p3.z); | |
println!("p3.product() = {}", p3.product()); // should be 6, not 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment