Jadow
December 18, 2021, 2:21am
1
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?
Cyborus
December 18, 2021, 2:34am
2
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
cuviper
December 18, 2021, 2:42am
3
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
Jadow
December 18, 2021, 3:15am
4
That's too bad! So how to get function name of f
duration compilation?
Jadow
December 18, 2021, 3:16am
5
I'll try the crate, thanks!
Cyborus
December 18, 2021, 3:20am
6
Well, if you know what function you're calling, then you already know the name
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");
Jadow
December 18, 2021, 3:30am
7
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
system
Closed
March 18, 2022, 3:55am
9
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.