我正在尝试将 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)
}
关于Rust:打印作为参数传入的函数的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68030477/