HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustMajor

Equivalent of __func__ or __FUNCTION__ in Rust?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
equivalent__function__rust__func__

Problem

In C and C++ you can get the name of the currently executing function through the __func__ macro with C99 & C++11 and ___FUNCTION___ for MSVC.

Is there an equivalent of this in Rust?

Example of __func__ in C:

#include "stdio.h"

void funny_hello() {
printf ("Hello from %s\n", __func__);
}

int main() {
funny_hello();
}


Outputs Hello from funny_hello.

Solution

You can hack one together with std::any::type_name.

macro_rules! function {
    () => {{
        fn f() {}
        fn type_name_of(_: T) -> &'static str {
            std::any::type_name::()
        }
        let name = type_name_of(f);
        name.strip_suffix("::f").unwrap()
    }}
}


Note that this gives a full pathname, so my::path::my_func instead of just my_func. A demo is available.

Code Snippets

macro_rules! function {
    () => {{
        fn f() {}
        fn type_name_of<T>(_: T) -> &'static str {
            std::any::type_name::<T>()
        }
        let name = type_name_of(f);
        name.strip_suffix("::f").unwrap()
    }}
}

Context

Stack Overflow Q#38088067, score: 60

Revisions (0)

No revisions yet.