【问题标题】:Rust: print the name of the function passed in as argumentRust:打印作为参数传入的函数的名称
【发布时间】:2021-06-18 06:39:42
【问题描述】:

我正在尝试将 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?
}

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

 ^ `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`

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

有没有办法做到这一点?

【问题讨论】:

  • 您要打印一个函数?为什么 ?你希望结果是什么?
  • @DenysSéguret 我期望的某种调试方式,类似于用 python 或 JS 之类的语言打印回调名称以知道在哪里调用的东西。

标签: rust


【解决方案1】:

有没有办法做到这一点?

是的。您可以使用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)
}

simplified example in playground具有多种功能

【讨论】:

    猜你喜欢
    • 2015-10-08
    • 2018-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    • 2022-10-01
    • 2012-04-13
    相关资源
    最近更新 更多