Crust of Rust: Subtyping and Variance
Channel: Jon Gjengset
Date: 2021-02-20

In this episode of Crust of Rust, we go over subtyping and variance — a niche part of Rust that most people don't have to think about, but which is deeply ingrained in some of Rust's borrow ergonomics, and occasionally manifests in confusing ways. In particular, we explore how trying to implement the relatively straightforward `strtok` function from C/C++ in Rust quickly lands us in a place where the function is more or less impossible to call due to variance!

0:00:00 Introduction
0:02:30 Practical variance in strtok
0:07:41 A simple strtok test
0:09:45 Implementing strtok
0:13:00 Why can't we call strtok?
0:17:26 Pretending to be the compiler
0:19:03 Shortening lifetimes
0:25:40 Subtypes
0:29:12 Covariance
0:33:15 Contravariance
0:42:14 Invariance
0:50:00 &'a mut T covariance in 'a
0:57:57 What went wrong in our strtok test?
1:02:24 Fixing strtok
1:07:34 Why is 'b: 'a not needed?
1:09:08 Shortening &'a mut and NLL
1:10:11 Is 'b: 'a implied for &'a &'b?
1:12:54 Variance, PhantomData, and drop check
1:28:06 Reasons for changing variance
1:30:47 for{'a} and variance
1:31:51 Mutating through *const T
1:33:29 NonNull{T}
1:35:26 How we got here

You can read more about subtyping and variance in the Rust reference @ https://doc.rust-lang.org/nightly/reference/subtyping.html or in the Nomicon @ https://doc.rust-lang.org/nomicon/subtyping.html.


Live version with chat: https://youtu.be/--wzpkTuCrA