Strategies for dyn trait objects with optional behavior?

I have a trait with optional behavior, and I'm trying to figure out how to use it behind a trait object.

trait Trait {
    fn required_behavior(&self);

    fn optional_behavior(&self)
    where
        Self: Optional;
}

trait Optional: Trait {}

Unfortunately, this trait is not dyn compatible. If I change the bound to Self: Optional + Sized then it is dyn compatible, but the optional_behavior method is understandably non-dispatchable.

If I move the optional method to the subtrait:

trait Trait {
    fn required_behavior(&self);
}

trait Optional: Trait {
    fn optional_behavior(&self);
}

then the trait is dyn compatible, but I need some way to determine whether the Trait is also Optional, and if so downcast a &dyn Trait to a &dyn Optional. OO languages provide a way to downcast, but AFAIK Rust does not.

I could provide a way to access the downcasted subtrait object from the supertrait:

trait Trait {
    fn required_behavior(&self);

    fn as_optional(&self) -> Option<&dyn Optional> {
        None
    }
}

trait Optional: Trait {
    fn optional_behavior(&self);
}

However, this is a bit awkward and feels non-idiomatic. (Iterator doesn't do this for DoubleEndedIterator, so rev() is unusable behind dyn Iterator AFAIK.)

Is there a better way?

In order to offer optional behavior through dyn, you must write a method that expresses that optionality. Your as_optional is how it is done (assuming you don’t want to just have a method that either does the optional thing immediately or returns an error).

rev requires Self: Sized

I discovered a bunch of crates that claim to add support for casting from a trait object to another trait object:

None of them seem to be widely used. Does anyone have any experience—good or bad—with any of these?

True, but these impls exist:

impl<I: Iterator + ?Sized> Iterator for &mut I {
    // ...
}

impl<'a, I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for &'a mut I {
    // ...
}

so if there was a way to downcast a &mut dyn Iterator to a &mut dyn DoubleEndedIterator then Iterator::rev() could be used.

This person arrived at the same solution as you.