3 ms·
Does the need for this arise, in some sense, because Rust doesn't offer classical inheritance and so no mechanism to indicate co/contra variance?
by michaelsbradley 10y ago
Does the need for this arise, in some sense, because Rust doesn't offer classical inheritance and so no mechanism to indicate co/contra variance?
- aturon 10y agoNo, it's more related to the fact that Rust allows you to use traits in both a statically- and dynamically-dispatched way. You can read some more on the topic here: http://aturon.github.io/blog/2015/09/28/impl-trait/ http://aturon.github.io/blog/2015/09/28/impl-trait/
- Gankro 10y agoRust does let you communicate variance (it's very important for lifetimes). Variance is determined based on a type's composition, and PhantomData can be used to specify variance that doesn't immediately follow by providing an "example" of what it should behave like. The only limitation of this approach is that you can't override the compiler's reasoning -- if it sees evidence for covariance, and you provide more evidence for contravariance it will just give up and pick invariance (which is of course strictly correct if both pieces of evidence are accurate). Also I guess you can't have bivariance but like... bivariance is so bad. All of Rust's standard collection and smaht pointer types are written in pure Rust and have relatively complex variance behaviour.
- andrewflnr 10y agoFor anyone else wondering what the deal is with "smaht pointers": https://www.reddit.com/r/rust/comments/3404ml/prepooping_your_pants_with_rust/cqrd0rq?context=3 https://www.reddit.com/r/rust/comments/3404ml/prepooping_you... I think I first saw the term on that thread but didn't stay long enough to see the explanation. It was driving me nuts! :)
- dbaupp 10y agoI'm not sure variance is at all related to this particular feature (maybe you could expand on your thinking?), but I also don't think the classical inheritance techniques for solving this problem are appropriate. I assume you're referring to, say, having an Iterator or Future base class and returning that. This unfortunately imposes costs like virtual calls and allocations, and is in fact already possible in Rust via trait objects (a function can return Box<Iterator<...>>, which is an allocation containing the data along with a vtable of virtual function pointers to manipulate that data). The impl trait feature is designed to allow returning closures and other unnameable/complicated types with no unnecessary cost, it's the same as returning a struct in C without compromising on programmer niceties.
- michaelsbradley 10y agoI probably misunderstood something, and it's been awhile since I looked closely at the language. Your reply, and the others to my comment, have been enlightening, thanks!