gpt4 book ai didi

rust - 在 trait 中定义一个返回 Self 的默认实现的方法

转载 作者:行者123 更新时间:2023-12-03 11:29:56 26 4
gpt4 key购买 nike

我想要以下功能

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));
}

( Playground )

这不编译:

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`

是否有可能改变方法使其起作用?这甚至可能让 trait 对象有一个返回 Self 的一些实现的方法吗? ?如果没有,为什么不呢?

最佳答案

实现 default在 trait 对象类型上,而不是在 trait 上:

trait Policy {
fn eval(&self, k: u32) -> bool;
}

impl dyn Policy {
fn default() -> Box<Self> {
Box::new(MaxPolicy { max: 2 })
}
}

也可以看看:
  • Why would I implement methods on a trait instead of as part of the trait?
  • 关于rust - 在 trait 中定义一个返回 Self 的默认实现的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62152943/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com