4 ms·
I think because returning two different types requires dynamic dispatch when using the returned objects, which requires Box; if the function only returns one ty
by tylerhou 8y ago
I think because returning two different types requires dynamic dispatch when using the returned objects, which requires Box; if the function only returns one type then that type can be determined at runtime and further function calls can be implemented with static dispatch instead.
- the_mitsuhiko 8y agoRust could generate a bespoke internal proxy type.
- Rusky 8y agoThat would still require dynamic dispatch of some kind.
- the_mitsuhiko 8y agoBut it wouldn’t require a heap allocation.
- lmm 8y agoWhere is the proxy implementation going to go if not the heap?
- GolDDranks 8y agoThe proxy object would have statically known size (maximum of the size of the types it dispatches between, plus some metadata such as a vtable pointer or an enum discriminant). Now, because you know the size statically, you can store it in the stack.
- shepmaster 8y agoUntil then, we use `Either` (https://stackoverflow.com/a/50204370/155423 https://stackoverflow.com/a/50204370/155423)
- leshow 8y agoTangentially, do you know why Rust never included an Either type? We have Result, which is great, but Either is useful for more things than errors (though that seems to be it's main use).
- steveklabnik 8y agoWe had it for a long time, as well as result, and literally no code used it, so we took it out. There’s a crate on crates.io for it if you want to use it for something.