Skip to content

Commit ae69217

Browse files
conradludgateehuss
authored andcommitted
begin rewriting chapter on subtyping
1 parent b5f018f commit ae69217

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/subtyping.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,45 @@
11
# Subtyping and Variance
22

3+
Rust uses lifetimes to track the relationships between borrows and ownership.
4+
However, a naive implementation of lifetimes would be either too restrictive,
5+
or permit undefined behaviour. Let's see a few examples:
6+
7+
```rust,ignore
8+
fn debug<'a>(a: &'a str, b: &'a str) {
9+
println!("a = {:?} b = {:?}", a, b)
10+
}
11+
12+
fn main() {
13+
let a: &'static str = "hello";
14+
{
15+
let b = String::from("world");
16+
let b = &b; // 'b has a shorter lifetime than 'static
17+
debug(a, b);
18+
}
19+
}
20+
```
21+
22+
In an overly restrictive implementation of lifetimes, since `a` and `b` have differeing lifetimes,
23+
we might see the following error:
24+
25+
```text
26+
error[E0308]: mismatched types
27+
--> src/main.rs:6:16
28+
|
29+
6 | debug(a, b);
30+
| ^
31+
| |
32+
| expected `&'static str`, found struct `&'b str`
33+
```
34+
35+
This is over-restrictive. In this case, what we want is to accept any type that lives "at least as long" as `<'a>`.
36+
This is what subtyping is intended to fix.
37+
38+
Let's define lifetime `'a` to be a `subtype` of lifetime `'b`, if and only if `'a` lives _at least as long_ as `'b`.
39+
We will denote this as `'a: 'b`
40+
41+
---
42+
343
Subtyping is a relationship between types that allows statically typed
444
languages to be a bit more flexible and permissive.
545

0 commit comments

Comments
 (0)