Crate type_path

source ·
Expand description

Guide

The crate has just one macro: type_path!. Check it out for syntax and details about what it returns.

You might be wondering why we’re using an absolute path in the following example:

use type_path::type_path;
assert_eq!(type_path!(::std::io::BufWriter), ["::", "std", "io", "BufWriter"]);

It’s because macros have no way of knowing the scope of the given item.

If it wasn’t required, the following would happen, because macros only have access to the literal Result tokens, and no type information/scope etc.

use std::io::Result;
assert_eq!(type_path!(Result), ["Result"]);

Now, the reliability aspect is gone, because even though the type exists, "Result" is extremely generic and almost certainly not what you want.

You can also have an “everything” path (although you probably won’t use this a lot):

assert_eq!(type_path!(::std::io::*), ["::", "std", "io", "*"]);

This doesn’t compile, since BufWrirer doesn’t exist:

type_path!(::std::io::BufWrirer);

Why?

  • Reliability: The type_path! macro will check if the path you entered is valid, at compile time. With other approaches, you can’t be sure that the path is valid.
  • No dependencies.
  • You can use it in a no-std environment,

Macros