3

I would like to have the following functionality

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)

This does not compile:

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`

Would it possible to alter the approach to make it work? Is this even possible for trait objects to have a method returning some implementation of Self? If not, why not?

Victor Ermolaev
  • 721
  • 1
  • 5
  • 16
  • Exactly _which_ type should `Policy::default()` return? – Shepmaster Jun 02 '20 at 13:22
  • Any type implementing `Policy`, that is why it is `Box`-ed. Even if one puts there a concrete type, say, `MaxPolicy`, it will not compile (https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=03fd001b07747366ac4d480613a650c5) – Victor Ermolaev Jun 02 '20 at 13:27

2 Answers2

2

Implement default on the trait object type, not on the trait:

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

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

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
0

I constructed a workaround which has a similar nice API

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

struct MaxPolicy {
    max: u32,
}

impl Policy for MaxPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MaxPolicy");
        k < self.max
    }
}

struct MinPolicy {
    min: u32,
}

impl Policy for MinPolicy {
    fn eval(&self, k: u32) -> bool {
        println!("MinPolicy");
        k > self.min
    }
}

enum PolicyEnum {
    Custom(Box<dyn Policy>),
    Default,
}

impl PolicyEnum {
    const DEFAULT: MaxPolicy = MaxPolicy { max: 4 };
}

impl Policy for PolicyEnum {
    fn eval(&self, k: u32) -> bool {
        match self {
            PolicyEnum::Custom(p) => p.eval(k),
            PolicyEnum::Default => Self::DEFAULT.eval(k),
        }
    }
}

Playground

With that, it's possible to do:

#[test]
fn default() {
    let p = PolicyEnum::Default;

    assert!(p.eval(3));
}

#[test]
fn custom() {
    let p = PolicyEnum::Custom(Box::new(MinPolicy{min: 4}));

    assert!(p.eval(5));
}
Victor Ermolaev
  • 721
  • 1
  • 5
  • 16