Rust 读取函数名的调研

文档列表见:Rust 移动端跨平台复杂图形渲染项目开发系列总结(目录) git

没这个功能很不方便日志记录。github

RFC: Add "function name macro" 四年前提出经过 function!提供相似C/C++编译器提供的__func__宏定义同样的功能,目前已合并,但还不可用。post

Equivalent of func or FUNCTION in Rust? 提供了一个临时解决办法:ui

#![feature(core_intrinsics)]

macro_rules! function {
    () => {{
        fn f() {}
        fn type_name_of<T>(_: T) -> &'static str {
            extern crate core;
            unsafe { core::intrinsics::type_name::<T>() }
        }
        let name = type_name_of(f);
        &name[6..name.len() - 4]
    }}
}

pub fn main() {
    (|| {
        mod module {
            pub trait Trait {
                fn function(&self) {
                    println!("{} (in {} [{}:{}:{}])",
                        function!(), module_path!(), file!(), line!(), column!()
                    );
                }
            }
            impl Trait for () {}
        }
        module::Trait::function(&());
    })()
}
复制代码
相关文章
相关标签/搜索