Rust:打印作为参数传入的函数名

ilm*_*moi 2 rust

我正在尝试将 args 打印到以下函数:

pub async fn loop_until_hit_rate_limit<'a, T, Fut>(
    object_arr: &'a [T],
    settings: &'a Settings,
    pool: &'a PgPool,
    f: impl Fn(&'a Settings, &'a PgPool, &'a T) -> Fut + Copy,
    rate_limit: usize,
) where
    Fut: Future<Output = anyhow::Result<()>>,
{
    // do stuff
    println!("args were: {}, {}, {}, {}, {}", object_arr, settings, pool, f, rate_limit) // <--- how do I make this work?
}
Run Code Online (Sandbox Code Playgroud)

天真的方法失败并出现以下错误(对于 {}):

 ^ `impl Fn(&'a Settings, &'a PgPool, &'a T) -> Fut + Copy` cannot be formatted with the default formatter
Run Code Online (Sandbox Code Playgroud)

或者这个错误(对于{:?}):

^ `impl Fn(&'a Settings, &'a PgPool, &'a T) -> Fut + Copy` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
Run Code Online (Sandbox Code Playgroud)

两者都有道理,但我不知道如何绕过它们。我找到了这个线程,但它只打印调用函数的名称,而不是作为 arg 传入的名称。

有没有办法做到这一点?

Den*_*ret 6

有没有办法做到这一点?

是的。您可以使用std::any::type_name.

所以你可以这样做:

pub async fn loop_until_hit_rate_limit<'a, T, Fut>(
    object_arr: &'a [T],
    settings: &'a Settings,
    pool: &'a PgPool,
    f: impl Fn(&'a Settings, &'a PgPool, &'a T) -> Fut + Copy,
    rate_limit: usize,
) where
    Fut: Future<Output = anyhow::Result<()>>,
{
    // do stuff
    fn type_name_of<T>(_: T) -> &'static str {
        std::any::type_name::<T>()
    }
    let f_name = type_name_of(f);
    println!("args were: {}, {}, {}, {}, {}", object_arr, settings, pool, f_name, rate_limit)
}
Run Code Online (Sandbox Code Playgroud)

具有各种功能的操场上的简化示例