From 8ebcf93556a9da28181e3d14316107660c316257 Mon Sep 17 00:00:00 2001 From: luojinming Date: Sun, 20 Sep 2020 12:46:05 +0800 Subject: [PATCH] add path_of macro --- examples/basic.rs | 2 ++ src/lib.rs | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/examples/basic.rs b/examples/basic.rs index f8cfb48..48c2cac 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -44,4 +44,6 @@ fn main() { name_of!(type i32), name_of!(type f64) ); + + println!("{}", path_of!(crate::greet)); } diff --git a/src/lib.rs b/src/lib.rs index a28d49f..f4b30b4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -140,6 +140,32 @@ macro_rules! name_of_type { }}; } +/// Takes the path of a type/mod/const.. as its path &str, +/// e.g. `path_of!(web::info::Foo)`. +/// +/// # Examples +/// +/// ``` +/// # #[macro_use] extern crate nameof; +/// use web::info::Foo; +/// +/// # fn main() { +/// +/// println!("struct path `{}`.", path_of!(web::info::Foo)); +/// +/// # } +/// ``` +#[macro_export] +macro_rules! path_of { + ($p: path) => {{ + let _ = || { + use $p; + }; + + stringify!($p) + }}; +} + #[cfg(test)] mod tests { fn test_fn() { @@ -180,6 +206,11 @@ mod tests { assert_eq!(name_of_type!(i32), "i32"); } + #[test] + fn path_of() { + assert_eq!(path_of!(test_fn), "test_fn"); + } + #[test] fn name_of_struct() { assert_eq!(name_of!(type TestStruct), "TestStruct");