Skip to content

Instantly share code, notes, and snippets.

@petertseng
Last active August 17, 2016 07:16
Show Gist options
  • Save petertseng/0b3928f0ee8881e94bf654d3f2153df9 to your computer and use it in GitHub Desktop.
Save petertseng/0b3928f0ee8881e94bf654d3f2153df9 to your computer and use it in GitHub Desktop.
space age - macros and Age<T>
use std::marker::PhantomData;
macro_rules! planet {
($planet: ident, $planetage: ident, $period: expr) => {
pub struct $planet;
impl Planet for $planet { fn period() -> f32 { $period } }
pub type $planetage = Age<$planet>;
};
}
pub trait Planet {
fn period() -> f32;
}
planet!(Mercury, MercuryAge, 0.2408467);
planet!(Venus, VenusAge, 0.61519726);
planet!(Earth, EarthAge, 1.0);
planet!(Mars, MarsAge, 1.8808158);
planet!(Jupiter, JupiterAge, 11.862615);
planet!(Saturn, SaturnAge, 29.447498);
planet!(Uranus, UranusAge, 84.016846);
planet!(Neptune, NeptuneAge, 164.79132);
pub struct Age<T> {
years: f32,
planet: PhantomData<T>,
}
impl <T: Planet> From<u64> for Age<T> {
fn from(seconds: u64) -> Self {
Age {
years: (seconds as f32) / 86400.0 / 365.25 / T::period(),
planet: PhantomData,
}
}
}
impl <T> Age<T> {
pub fn years(&self) -> f32 {
self.years
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment