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

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

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

 ^ `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但它只打印调用函数的名称,而不是作为参数传入的名称。

有办法吗?

最佳答案

Is there a way to do this?

是的。您可以使用 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具有多种功能

关于Rust:打印作为参数传入的函数的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68030477/

相关文章:

string - 将 PathBuf 转换为 String 时是否有避免克隆的方法?

rust - 如何通过编译器选项覆盖常量?

rust - 从 Rust 调用 OpenACC 代码不在 GPU 上运行

reference - 如何将引用的元组转换为元组的引用?

rust - 字符串文字是不可变的吗?

rust - 如何区分多次出现的选项和带有 structopt 的后续可选参数?

rust - 调用 Rust init 函数时获取 "Cannot deserialize the contract state"

rust - 在 rust 中访问 BigUint 的各个数字

string - 如何更新字符串中的字符?

rust - 如何获取 Arc<[T]> 的子切片