我希望拥有以下功能
trait Policy {
fn eval(&self, k: u32) -> bool;
fn default() -> Box<dyn Policy>
where
Self: Sized,
{
Box::new(MaxPolicy { max: 2 })
}
}
struct MaxPolicy {
max: u32,
}
impl Policy for MaxPolicy {
fn eval(&self, k: u32) -> bool {
println!("MaxPolicy");
k < self.max
}
}
#[test]
fn max_policy() {
let p = MaxPolicy { max: 2 };
assert!(!p.eval(3));
}
#[test]
fn default_policy() {
let p = Policy::default();
assert!(!p.eval(3));
}
(游乐场)
以下内容无法编译:
error[E0283]: type annotations needed
--> src/lib.rs:31:13
|
4 | fn default() -> Box<dyn Policy>
| -------
5 | where
6 | Self: Sized,
| ----- required by this bound in `Policy::default`
...
31 | let p = Policy::default();
| ^^^^^^^^^^^^^^^ cannot infer type
|
= note: cannot resolve `_: Policy`
是否有可能改变方法来使其工作?对于特质对象来说,是否有可能有一个返回Self
的实现方法呢?如果不能,为什么呢?
Policy::default()
应该返回哪种类型? - ShepmasterPolicy
接口的类型,都需要被Box
包装。即使将具体类型,例如MaxPolicy
放在那里,它也无法编译通过(https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=03fd001b07747366ac4d480613a650c5)。 - Victor Ermolaev