Ensure that at least one of multiple trait methods is overriden

So I have a trait Searchable for things that can be optimized using branch&bound search or similar methods. The trait has three methods that are relevant for this question:

trait Searchable{
  
  fn lower_bound(&self) -> Quality;

  fn is_solved(&self) -> bool {
    self.quality().is_some()
  }

  fn quality(&self) -> Option<Quality> {
    if self.is_solved() {
      Some(self.lower_bound())
    } else {
      None
  }
  // other methods
}

As you can see it is possible to express is_solved in terms of quality and the other way around.
Now this is nice since the implementing type can override one or both of these methods and get the rest for free. But if both methods are left with the default impl we have a problem since they recurse forever.
Does anyone know if there is any trick I can use to avoid the problem without giving up on the convenience of the default impls?

Thanks in advance!

Personally I'd just pick one method (probably is_solved) to be required and one to be defaulted. I don't think any workaround is going to be simpler or more convenient than that, at least not when the methods are as straightforward as they are here.

4 Likes

You are right that is probably the way to go. I was just curious if there was some fancy solution I was unaware of.

1 Like

There's no built-in solution for this. See the links here for some past discussions/proposals:

4 Likes

Thanks for the link. I knew I could not have been the first to encounter this but damn an issue from 2013 is straightup ancient for rust.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.