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

标签 rust traits

我想要以下功能

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/

    相关文章:

    rust - 宏匹配 token 递归扩展

    PHPUnit 模拟特征

    file - 如何逐行读取可能不是有效 UTF-8 的文件?

    collections - 在迭代器上调用map时如何消除部分移动

    rust - 为什么 Rust 不能做更复杂的类型推断?

    multithreading - 将闭包(返回具有特征的结构)发送到线程会导致大小错误

    generics - 为什么在关联类型上不识别除第一个之外的 super 特征边界?

    generics - 何时以及为何使用 AsRef<T> 而不是 &T

    适用于数据分析程序的 python GUI 框架/库

    Scala 特征 : defining nested attributes