Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


I 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)
      }
  }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: