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?
6 posts - 4 participants
Read full topic
| # | Наименование новости | Тональность | Информативность | Дата публикации |
|---|---|---|---|---|
| 1 | Type erasure and dyn lifetime in a NonNull/Box struct field | 0 | 8.55 | 04-10-2026 |
| 2 | Trait object with associated types in field - requires generic param? | 0 | 11.08 | 07-10-2026 |
| 3 | Limitations of `min_specialization` when specializing a generic implementation? | 0 | 9.38 | 04-10-2026 |
| 4 | Why no Dependent Matrix Type? | 0 | 5.16 | 08-10-2026 |
| 5 | Crate async_trait - error future created by async block is not Send | 0 | 5.4 | 05-10-2026 |
| 6 | Optimization of inlined functions returning Result? | 0 | 7.36 | 06-10-2026 |
| 7 | Does my lockfree stack impl look correct? | 0 | 6.06 | 05-10-2026 |
| 8 | Calling static C++ method from Rust | 0 | 9.94 | 04-10-2026 |
| 9 | Arena's and alignment | 0 | 7.3 | 04-10-2026 |
| 10 | What's everyone working on this week (41/2026)? | 0 | 20.34 | 06-10-2026 |