gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:29:09 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com