Macros: Call static trait method on a passed-in type


#1

In the simplified method below, within the macro test, how can I invoke the static method len() on a passed-in type?

trait Test {
  fn len() -> usize { 1 }
}
impl Test for u8 {}

macro_rules! test {
    ($item_ty:ty) => (
        println!("{}", $item_ty::len());
    )
}

fn main() {
    test!(u8); // ERROR
    println!("{}", u8::len()); // runs fine
}

Playground

The code above gives the error

<anon>:8:24: 8:32 error: unexpected token: `u8`
<anon>:8         println!("{}", $item_ty::len());
                                ^~~~~~~~

#2
<$item_ty>::len()

The <...> in expression position turns any type into a path. u8::len parses cleanly because it looks like a regular path.


#3

Ah, thanks! I was being very silly. I had also tried (u8 as Test)::len() which was giving an error about a type being unexpected there – I was using the wrong brackets!