【发布时间】:2020-01-01 00:23:15
【问题描述】:
使用包含返回对Self 的引用的方法的特征对象的正确方法是什么?以下代码
trait Foo {
fn gen(&mut self) -> &Self;
fn eval(&self) -> f64;
}
struct A {
a : f64,
}
impl Foo for A {
fn gen(&mut self) -> &Self {
self.a = 1.2;
self
}
fn eval(&self) -> f64 {
self.a + 2.3
}
}
struct B;
impl Foo for B {
fn gen(&mut self) -> &Self {
self
}
fn eval(&self) -> f64 {
3.4
}
}
fn bar(f : &dyn Foo) {
println!("Result is : {}",f.eval());
}
fn main() {
let mut aa = A { a : 0. };
bar(aa.gen());
let mut bb = B;
bar(bb.gen());
}
给出编译器错误
error[E0038]: the trait `Foo` cannot be made into an object
--> src/main.rs:30:1
|
3 | fn gen(&mut self) -> &Self;
| --- method `gen` references the `Self` type in its parameters or return type
...
30 | fn bar(f : &dyn Foo) {
| ^^^^^^^^^^^^^^^^^^^^ the trait `Foo` cannot be made into an object
现在,我们可以通过以下两种方式中的至少一种来解决此问题。或者,我们可以将gen的定义修改为:
trait Foo {
fn gen(&mut self) -> &Self where Self : Sized;
fn eval(&self) -> f64;
}
或者,我们可以将bar的定义修改为:
fn bar<F>(f : &F) where F : Foo + ?Sized {
println!("Result is : {}",f.eval());
}
也就是说,我不明白两者之间的区别以及应该使用什么情况或是否应该使用其他方法。
【问题讨论】:
标签: rust