Skip to content

Commit 8f88efd

Browse files
conradludgateehuss
authored andcommitted
add demos for box and fn
1 parent 2c8ff4f commit 8f88efd

File tree

1 file changed

+57
-4
lines changed

1 file changed

+57
-4
lines changed

src/subtyping.md

+57-4
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ fn main() {
120120
let world = String::from("world");
121121
assign(&mut hello, &world);
122122
}
123-
println!("{}", hello);
123+
println!("{}", hello); // use after free 😿
124124
}
125125
```
126126

@@ -258,9 +258,24 @@ So the compiler decides that `&'static str` can become `&'b str` if and only if
258258
`&'static str` is a subtype of `&'b str`, which will hold if `'static: 'b`.
259259
This is true, so the compiler is happy to continue compiling this code.
260260

261-
`Box<T>` is also *covariant* over `T`. This would make sense, since it's supposed to be
262-
usable the same as `&T`. If you try to mutate the box, you'll need a `&mut Box<T>` and the
263-
invariance of `&mut` will kick in here.
261+
As it turns out, the argument for why it's ok for Box (and Vec, Hashmap, etc.) to be covariant is pretty similar to the argument for why it's ok for lifetimes to be covariant: as soon as you try to stuff them in something like a mutable reference, they inherit invariance and you're prevented from doing anything bad.
262+
263+
However Box makes it easier to focus on by-value aspect of references that we partially glossed over.
264+
265+
Unlike a lot of languages which allow values to be freely aliased at all times, Rust has a very strict rule: if you're allowed to mutate or move a value, you are guaranteed to be the only one with access to it.
266+
267+
Consider the following code:
268+
269+
```rust,ignore
270+
let hello: Box<&'static str> = Box::new("hello");
271+
272+
let mut world: Box<&'b str>;
273+
world = hello;
274+
```
275+
276+
There is no problem at all with the fact that we have forgotten that `hello` was alive for `'static`,
277+
because as soon as we moved `hello` to a variable that only knew he it was alive for `'b`,
278+
**we destroyed the only thing in the universe that remembered it lived for longer**!
264279

265280
Only one thing left to explain: function pointers.
266281

@@ -303,6 +318,44 @@ Covariance doesn't work here. But if we flip it around, it actually *does*
303318
work! If we need a function that can handle `&'static str`, a function that can handle *any* reference lifetime
304319
will surely work fine.
305320

321+
Let's see this in practice
322+
323+
```rust,compile_fail
324+
# use std::cell::RefCell;
325+
thread_local! {
326+
pub static StaticVecs: RefCell<Vec<&'static str>> = RefCell::new(Vec::new());
327+
}
328+
329+
/// saves the input given into a thread local `Vec<&'static str>`
330+
fn store(input: &'static str) {
331+
StaticVecs.with(|v| {
332+
v.borrow_mut().push(input);
333+
})
334+
}
335+
336+
/// Calls the function with it's input (must have the same lifetime!)
337+
fn demo<'a>(input: &'a str, f: fn(&'a str)) {
338+
f(input);
339+
}
340+
341+
fn main() {
342+
demo("hello", store); // "hello" is 'static. Can call `store` fine
343+
344+
{
345+
let smuggle = String::from("smuggle");
346+
347+
// `&smuggle` is not static. If we were to call `store` with `&smuggle`,
348+
// we would have pushed an invalid lifetime into the `StaticVecs`.
349+
// Therefore, `fn(&'static str)` cannot be a subtype of `fn(&'a str)`
350+
demo(&smuggle, store);
351+
}
352+
353+
StaticVecs.with(|v| {
354+
println!("{:?}", v.borrow()); // use after free 😿
355+
});
356+
}
357+
```
358+
306359
And that's why function types, unlike anything else in the language, are
307360
**contra**variant over their arguments.
308361

0 commit comments

Comments
 (0)