File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1
1
# Subtyping and Variance
2
2
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
+
3
43
Subtyping is a relationship between types that allows statically typed
4
44
languages to be a bit more flexible and permissive.
5
45
You can’t perform that action at this time.
0 commit comments