Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of __func__ or __FUNCTION__ in Rust?

Tags:

macros

rust

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.

like image 675
PureW Avatar asked Jun 28 '16 23:06

PureW


4 Answers

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

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[..name.len() - 3]
    }}
}

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

like image 84
Veedrac Avatar answered Nov 16 '22 17:11

Veedrac


There was an RFC about this, but it was never agreed upon or implemented.

The rationale for its absence:

"In general I don't think any of us have given an inordinate amount of thought to these "debugging related" macros in terms of long term stability. Most of them seem fairly harmless, but committing to provide all of them for all Rust programs forever is a strong commitment to make. We may want to briefly consider the story of these macros in conjunction with considering adding this new macro."

Maybe Rust will have something comparable in the future,
but for now you will need to rely on your own tagging.

side note: __FUNCTION__ is non standard, __func__ exists in C99 / C++11.

like image 33
Trevor Hickey Avatar answered Nov 16 '22 19:11

Trevor Hickey


Adding to Veedrac's answer, you can get the function's name without its full path by adding this:

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

        // Find and cut the rest of the path
        match &name[..name.len() - 3].rfind(':') {
            Some(pos) => &name[pos + 1..name.len() - 3],
            None => &name[..name.len() - 3],
        }
    }};
}

You will get my_func instead of my::path::my_func for example.

like image 9
Alexis Avatar answered Nov 16 '22 18:11

Alexis


It appears that function_name crate will do this.

https://docs.rs/function_name/latest/function_name/

The example from the docs is

use ::function_name::named;

#[named]
fn my_super_duper_function ()
{
    assert_eq!(
        function_name!(),
        "my_super_duper_function",
    );
}

I am not involved with the project and have not actually tried it yet.

like image 4
Troy Daniels Avatar answered Nov 16 '22 19:11

Troy Daniels