Crust of Rust: The Drop Check
Channel: Jon Gjengset
Date: 2021-03-13

In this episode of Crust of Rust, we go over the "drop check" — another niche part of Rust that most people don't have to think about, but which rears its moderately attractive head occasionally when you use generic types in semi-weird ways. In particular, we explore how to implement a Norwegian version of Box (which is really just Box with a different name), and find that the straightforward implementation is not quite as flexible as the standard Box is due to the drop check. When we fix it, we then make it _too_ flexible, and open ourselves the type up to undefined behavior. Which, in turn, we use the drop check to fix. Towards the end, we go through a particularly interesting example at the intersection of the drop check and variance in the form of (ab)using std::iter::Empty.

0:00:00 Introduction
0:01:39 Boks: A Norwegian Box
0:04:22 Freeing a Boks
0:05:56 Dereferencing a Boks
0:09:40 Boks is too restrictive
0:26:52 Boks is not restrictive enough
0:35:35 PhantomData and may_dangle
0:36:32 What if Oisann didn't touch T?
0:37:30 Can I write PhantomData myself?
0:38:10 Boks isn't covariant!
0:43:49 Boks isn't covariant (in code)!
0:48:10 PhantomData T without holding a T
0:51:08 std::iter::Empty and variance
1:07:34 Why the Empty example compiles
1:13:40 Recap: what are all the bits?
1:15:47 Unnecessary Complexity?

You can read more about subtyping and variance in the Rustonomicon @ https://doc.rust-lang.org/nomicon/dropck.html.

Live version with chat: https://youtu.be/Das3XSWo1GU