Type system: covariance/contravariance?


#1

After reading The Book, I was wondering if it presented a dumbed down version of the type system… I didn’t see anything about covariant or contravariant type parameters. Is this supported in Rust or is everything invariant only? i.e. https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)


#2

The short answer is that there is no subtyping in Rust :slight_smile:

The long answer is that there is subtyping in Rust, but only for lifetimes, and there are variance rules about them (automatically derived from the data type definitions). However in practice you don’t think about them most of the time, because everything just works (I’ve written a moderate amount of Rust code, and I think I know about lifetime variance only in theory).


#3

See also the Rustonomicon chapter on subtyping and variance.


#4

There was a talk about that by @pnkfelix at Rustfest. You can find the slides here (and hopefully the video will be up soon as well).