How to write macros to derive traits for base types

Can you derive a Trait for a base type such as bool or u64 ?

I'm trying to wrap a C library and it has functions like

do_stuff_bool
do_stuff_int8

and I'd like to generate traits for the base types.

Sure!

trait MyTrait {
    fn foo(self) -> Self;
}

macro_rules! impl_my_trait {
    ( $typ:ty ) => {
        impl MyTrait for $typ {
            fn foo(self) -> Self {
                1 + self
            }
        }
    };
}

impl_my_trait!(u8);
impl_my_trait!(u16);
impl_my_trait!(u32);
impl_my_trait!(u64);
impl_my_trait!(u128);

playground

1 Like

Hey, thanks a lot for the quick answer, one of the things I'm hoping to do is match on a parameter type and call a different function
for example

macro_rules! impl_my_trait {
    ( $typ:ty ) => {
        impl MyTrait for $typ {
            fn foo(self) {
// when typ is bool call_func_in_C_BOOL(param);
// when typ is u8 call_func_in_C_UINT8(param);
            }
        }
    };
}

You can't really concatenate them, so you'll have to give the function name as another paramter:

trait MyTrait {
    fn foo(self) -> Self;
}

fn foo_u8(val: u8) -> u8 {
  1 + val
}
fn foo_u16(val: u16) -> u16 {
  1 + val
}
fn foo_u32(val: u32) -> u32 {
  1 + val
}
fn foo_u64(val: u64) -> u64 {
  1 + val
}

macro_rules! impl_my_trait {
    ( $typ:ty, $func:ident ) => {
        impl MyTrait for $typ {
            fn foo(self) -> Self {
                $func(self)
            }
        }
    };
}

impl_my_trait!(u8, foo_u8);
impl_my_trait!(u16, foo_u16);
impl_my_trait!(u32, foo_u32);
impl_my_trait!(u64, foo_u64);

playground

3 Likes