2. Control and Safety
• C++
More control, less safety
• Java
Less control, more safety
• Rust
More control, more safety
3. Users
• Rust
Rust compiler is written in Rust
• Servo
Parallel browser engine
• Dropbox
Cloud file storage
• More on
https://www.rust-lang.org/en-US/friends.html
29. Compile time check
| let b = &a[0];
| - immutable borrow
| a.push(2);
| ^ mutable borrow
30. Borrow is scoped
let mut a = vec![];
a.push(1);
{
let b = &a[0];
b; // this is okay!
}
a.push(2); // this too!
31. Aliasing XOR Mutation
• Multiple immutable borrows
• Or single mutable borrow
• This is why &mut T cannot be copied
32. Function
fn get(v: &Vec<i32>, i: usize)
-> &i32 { &v[i] }
let mut a = vec![];
a.push(1);
let b = get(&a, 0);
a.push(2);
33. Lifetime
fn get<’a>(v: &’a Vec<i32>,
i: usize)
-> &’a i32 { &v[i] }
let mut a = vec![];
a.push(1);
let b = get(&a, 0);
a.push(2);
34. Lifetime subtyping
• If ’a: ’b (’a outlives ’b)
&’a T <: &’b T
• Converse is also true:
If &’a T <: &’b T
’a: ’b
35. Lifetime inference
fn get<’a>(v: &’a Vec<i32>,
i: usize)
-> &’a i32 { &v[i] }
let b: &’x i32 = get(&’y a, 0);
// what is relationship between
// ’x and ’y?
36. Inference steps
• fn get <: get
• &’a T -> &’a U <: &’y T -> &’x U
• &’y T <: &’a T, &’a U <: &’x U
• ’y: ’a, ’a: ’x
• ’y: ’x
37. Lifetime inference result
let b: &’x i32 = get(&’y a, 0);
// ’y outlives ’x
// a is borrowed as long as
// b is in scope
// which was to be demonstrated