5 ms·
Sorry, based on the replies I'm getting I did not make myself clear. I only want to use Either in cases like the following. fn some_func() -> impl SomeTrai
by benschulz 5y ago
Sorry, based on the replies I'm getting I did not make myself clear. I only want to use Either in cases like the following.
fn some_func() -> impl SomeTrait {
if some_condition {
Either::Left(a)
} else {
Either::Right(b)
}
}
Both a and b will implement SomeTrait which is all callers care about. However, because they're structurally different they must be wrapped in an Either that delegates all methods from SomeTrait to a or b respectively.
- codeflo 5y agoI don't think that would work in general: trait methods can have signatures for which you can't synthesize an implementation for the sum type (something that takes a second Self as an argument, like std::ops::Add, comes to mind). For object-safe traits where this would be possible, you can at least do this at the cost of an allocation, as you probably know: fn some_func() -> Box<dyn SomeTrait> { if some_condition { Box::new(a) } else { Box::new(b) } }