如何在泛型函数中请求和使用结构(没有结构实例!)?
How to request and use a struct (without a struct instance!) inside a generic function?
我有这个代码:
fn func<T, U>(f: T) where T: Fn()-> U, U: MyTrait {
let state = f();
// ...
}
f
这里只是来自某个结构的特征 MyTrait
的 new
函数。我想要一个函数,它适用于每个实现 MyTrait
的结构,并且有一个 new
方法用于我想为 state
.
调用的那个特征
如何将结构(不是具有该结构类型的值)传递给函数,并限制为该结构实现的特定特征?
您不需要传递任何参数; 类型参数 U
您已经拥有的就是您所需要的。
fn func<U>(...)
where
U: MyTrait
{
...
let state = U::new();
...
}
或者您的意思是您想要 Fn() -> U
的通用实现?这更容易:U::new
已经是这样了。使用 Default
作为特征的示例,但您可以以相同的方式使用任何特征:
use std::fmt::Debug;
fn print_instance<T: Debug, F: Fn() -> T>(f: F) {
println!("{:?}", f());
}
fn print_default<T: Debug + Default>() {
print_instance::<T, _>(Default::default);
}
fn main() {
print_default::<Vec<i32>>();
print_default::<f32>();
}
我有这个代码:
fn func<T, U>(f: T) where T: Fn()-> U, U: MyTrait {
let state = f();
// ...
}
f
这里只是来自某个结构的特征 MyTrait
的 new
函数。我想要一个函数,它适用于每个实现 MyTrait
的结构,并且有一个 new
方法用于我想为 state
.
如何将结构(不是具有该结构类型的值)传递给函数,并限制为该结构实现的特定特征?
您不需要传递任何参数; 类型参数 U
您已经拥有的就是您所需要的。
fn func<U>(...)
where
U: MyTrait
{
...
let state = U::new();
...
}
或者您的意思是您想要 Fn() -> U
的通用实现?这更容易:U::new
已经是这样了。使用 Default
作为特征的示例,但您可以以相同的方式使用任何特征:
use std::fmt::Debug;
fn print_instance<T: Debug, F: Fn() -> T>(f: F) {
println!("{:?}", f());
}
fn print_default<T: Debug + Default>() {
print_instance::<T, _>(Default::default);
}
fn main() {
print_default::<Vec<i32>>();
print_default::<f32>();
}