Rust:打印传入参数的函数名称

3

我试图打印出以下函数的参数:

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?
}

天真的方法对于任何一个大括号都会失败,并给出以下错误信息:
 ^ `impl Fn(&'a Settings, &'a PgPool, &'a T) -> Fut + Copy` cannot be formatted with the default formatter

或者出现这个错误(对于 {:?}):
^ `impl Fn(&'a Settings, &'a PgPool, &'a T) -> Fut + Copy` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`

这两种方法都是有道理的,但我不确定如何解决它们。我找到了这个线程,但它只打印调用函数的名称,并没有打印传入的函数。

有没有办法做到这一点?


2
你想要打印一个函数?为什么?你想要得到什么结果? - Denys Séguret
@DenysSéguret,我认为这是某种调试工具,类似于在像Python或JS这样的语言中打印回调函数名称以了解所调用的内容。 - Masklinn
1个回答

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)
}

具有各种类型函数的Playground简化示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接