4 ms·
Can someone explain to me why rust decided not to support pattern matching with different types? Suchas: let x = Bus(); match x{ Car => ... Bus => ..
by randyrand 10y ago
Can someone explain to me why rust decided not to support pattern matching with different types?
Suchas:
let x = Bus();
match x{
Car => ...
Bus => ...
Person => ...
}
You would need to have runtime type information of course, this could be a compiler flag.
- elihu 10y agoBecause rust is statically typed, and "x" has to have a concrete type known at compile time? Maybe there's a use case for matching trait objects against types to get back the original type. But, I think you could do the same thing by adding a trait method that returns Option<T> for some desired type T. If the object wasn't that type, it could just return None.
- tatterdemalion 10y agoAnd this is actually implemented by the Any trait. https://doc.rust-lang.org/std/any/trait.Any.html https://doc.rust-lang.org/std/any/trait.Any.html
- Manishearth 10y agohttps://doc.rust-lang.org/std/any/trait.Any.html#method.downcast_ref https://doc.rust-lang.org/std/any/trait.Any.html#method.down... ? :)
- stouset 10y agoWhy can't you already do this with an enum? Rust isn't go. You don't have to break out of the type system because it doesn't have generics.
- Manishearth 10y agoRust has static types with generics and algebraic data types. 99% of the use cases for that get covered. It has trait objects for when you need runtime type information, but they're used very rarely and you can make that pattern work with a chain of `downcast_ref` if lets or obviate its need by implementing methods.