by s3cur3 · 5y ago · 0 comments
Two things stood out to me here as being really nice for someone coming from C++:
- Implicit upcasting to convert `[Derived]` to `[Base]` in O(1).
- Checked conversions convert `[T]` to `[U]?` in O(N) via `a as [U]` in O(n).
These are both operations I've manually written the C++ code to do, because there's no ergonomic way to do it with `std::vector`.
The upcast is type sound, unlike Java, but at the cost of an extra indirection, and a big hit for the first mutation after upcast. I would have been tempted to instead just have immutable array references that could be freely upcast, but this is also an elegant and safe solution.
E.g., given an array of Animal, you’d like to see if you can convert it to an array of Dog. Neither the compiler nor the runtime stores information on the array itself to say “it just so happens that the concrete Animal type of all the things I hold is [Dog/Cat/a mix of both],” so you have to go through the elements one by one.