结构是否有可能引用具有泛型方法的特征对象,而不使结构本身通用?
trait Foo {
fn generic_method<T>(&self) {}
}
struct MyFoo {}
impl Foo for MyFoo {}
struct Bar<'a> {
my_foo: &'a mut (Foo + 'a),
}
impl<'a> Bar<'a> {
fn new(my_foo: &'a mut Foo) -> Self {
Self { my_foo }
}
}
此代码给出了错误:
error[E0038]: the trait `Foo` cannot be made into an object
--> src/main.rs:9:5
|
9 | my_foo: &'a mut (Foo + 'a),
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Foo` cannot be made into an object
|
= note: method `generic_method` has generic type parameters
error[E0038]: the trait `Foo` cannot be made into an object
--> src/main.rs:13:5
|
13 | fn new(my_foo: &'a mut Foo) -> Self {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Foo` cannot be made into an object
|
= note: method `generic_method` has generic type parameters
答案 0 :(得分:0)
这是不可能的,因为事先不知道generic_method
的所有可能的实例化,因此编译器无法为generic_method
生成适当的vtable。
正如您所提到的,您可以改为struct
通用:
struct Bar<'a, T: Foo + 'a> {
my_foo: &'a mut T
}
impl<'a, T: Foo> Bar<'a, T> {
fn new(my_foo: &'a mut T) -> Self {
Self {my_foo}
}
}