Skip to content

Instantly share code, notes, and snippets.

@Kimundi
Forked from anonymous/playground.rs
Created April 3, 2017 15:49
Show Gist options
  • Save Kimundi/baaeb749c8f5b5b2d255389bf9630bdd to your computer and use it in GitHub Desktop.
Save Kimundi/baaeb749c8f5b5b2d255389bf9630bdd to your computer and use it in GitHub Desktop.
Shared via Rust Playground
#![feature(specialization)]
use std::fmt::*;
trait Maybe<T: ?Sized> {
fn implements_this(&self) -> bool;
fn fmt(&self, &mut Formatter) -> Result;
}
macro_rules! impl_maybe {
($t:path) => {
impl<T: ?Sized> Maybe<$t> for T {
default fn implements_this(&self) -> bool { false }
default fn fmt(&self, _: &mut Formatter) -> Result {
println!("nah");
Ok(())
}
}
impl<T: ?Sized + $t> Maybe<$t> for T {
fn implements_this(&self) -> bool { true }
fn fmt(&self, f: &mut Formatter) -> Result {
println!("ok");
<Self as $t>::fmt(self, f)
}
}
}
}
impl_maybe!(Debug);
impl_maybe!(Display);
impl_maybe!(LowerHex);
trait MaybeAll: Maybe<Debug> + Maybe<Display> + Maybe<LowerHex> {}
impl<T: ?Sized> MaybeAll for T
where T: Maybe<Debug> + Maybe<Display> + Maybe<LowerHex> {}
fn rtformat(s: &str, args: &[&MaybeAll]) {
for (c, t) in s.chars().zip(args) {
match c {
'd' => println!("{:?}", t)
}
}
}
fn main() {
rtformat("dDhh", &[&123u8, &"test", &0xffu8, &0xffu8]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment