How to get function name?

fn learn_rust(){
        println!("I am learning rust...");
    }
fn get_function_name(f: fn()){
        f();
    }
fn main(){
        get_function_name(learn_rust);
    }

How to get function name of parameter f inside function get_function_name in runtime?

Function pointers have no knowledge of their name, the names of functions only exist in the source code. Once the code is compiled that data is lost.

1 Like

It might be possible with something like backtrace::resolve, but I couldn't get that to work with the function pointer in your example.

1 Like

That's too bad! So how to get function name of f duration compilation?

I'll try the crate, thanks!

Well, if you know what function you're calling, then you already know the name :slight_smile:
You could either put it in a const:

const LEARN_RUST: &str = "learn_rust";

Or use stringify!

let name = stringify!(learn_rust);
assert_eq!(name, "learn_rust");

:rofl:
Is there any way to parse function name from parameter f? Is it also impossible?

A fn() is just a pointer to some machine code and has no extra information like the function name or signature. It's literally just a pointer to some machine code.

However, each function item has its own unique type, so if you make your code generic over some F: Fn(), you can use std::any::type_name() to get the name of its type.

fn learn_rust() {
    println!("I am learning rust...");
}

fn get_function_name<F>(_: F) -> &'static str
where
    F: Fn(),
{
    std::any::type_name::<F>()
}

fn main() {
    println!("{}", get_function_name(learn_rust));
}

(Playground)

Output:

playground::learn_rust

That said, this sounds like an X-Y question... Once you have a function's name, what will you do with it?

6 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.