Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 25 - Borrowing in practice: functions, iteration, and lifetimes

One arrow reaching a box and another blocked before it

Announcements




Learning Objectives

By the end of today, you should be able to:

  • Choose between &T, &mut T, and T for a function parameter
  • Use * to read or write through a reference
  • Change every element of a vector in place with iter_mut() and *
  • Bracket a value's lifetime against a borrow of it, and say whether a call site compiles
  • Read 'a in a function signature and say what it promises

Three things a function can ask for

Every function signature makes a choice about the data you hand it. There are three.

1. "Let me look at it." fn midpoint(v: &Vec<i32>)

The function gets an address it can read from but not write or move.

2. "Let me change it." fn add_zero(v: &mut Vec<i32>)

Also an address, but with "edit access".

3. "Give it to me." fn consume(v: Vec<i32>)

The function gets the data itself, and the caller's variable is finished: it moved.

When a function asks for option 3, the caller still has a choice: hand over the original, or hand over v.clone() and keep the original.

Why would you ever hand over ownership?

consume didn't need to. It read one number, and a reference would have done. Functions ask for T when they're going to put the value somewhere that outlives the call.

Into a collection:

#![allow(unused)]
fn main() {
fn enroll(roster: &mut Vec<String>, name: String) {
    roster.push(name);
}
}

Try name: &String and push refuses: "expected String, found &String". The vector holds Strings.

Into a struct:

#![allow(unused)]
fn main() {
struct Player { name: String, score: u32 }

fn new_player(name: String) -> Player {
    Player { name, score: 0 }
}
}

Same shape. The Player goes back to the caller and lives on, so the name has to live inside it.

A reference is a loan, and a loan can't go in a box that outlives it. That's why constructors take String, and why .to_string() keeps showing up right before a struct literal.

What each argument costs

Our first fix for ownership errors was to .clone(), and that often works. So why not clone whenever the compiler complains?

Let's see the same one-line body, one million elements, once by reference and once by clone.

fn midpoint_ref(v: &Vec<i32>) -> usize {
    v.len() / 2
}

fn midpoint_own(v: Vec<i32>) -> usize {
    v.len() / 2
}

use std::time::Instant;

fn main() {
    let mut my_vec = Vec::with_capacity(1_000_000);
    for i in 0..1_000_000 {
        my_vec.push(i);
    }

    let time = Instant::now();
    let mid = midpoint_ref(&my_vec);          // pass a reference
    println!("by reference: {:?}", time.elapsed());

    let time = Instant::now();
    let mid2 = midpoint_own(my_vec.clone());   // hand over a copy
    println!("by clone:     {:?}", time.elapsed());

    println!("{} {}", mid, mid2);
}
#![allow(unused)]
fn main() {
fn midpoint_ref(v: &Vec<i32>) -> usize {
    v.len() / 2
}

fn midpoint_own(v: Vec<i32>) -> usize {
    v.len() / 2
}
}

main builds a vector of a million numbers, then times midpoint_ref(&my_vec) against midpoint_own(my_vec.clone()).

Why is the second one so much slower?

clone() copies all elements to a new space on the heap, and then throws them away.

Passing a reference copies 8 bytes. Cloning copies 4 megabytes.

All the trade-offs

HowSpeedFunction can modify?Caller keeps it?
&T, shared referenceFastNoYes
&mut T, mutable referenceFastYesYes
T, given awayFastYesNo
T, but cloned firstSlowYesYes

So which should you use?

Rules of thumb:

  1. Start with &T. Most functions only need to look
  2. If the function has to change the caller's data, &mut T
  3. If the function stores the data somewhere that outlives the call, take it: T
  4. Reach for .clone() only when you need two copies that will diverge: one gets changed, the other stays put. Know what it costs

Try it. For each, which signature?

  1. A function that prints a vector
  2. A function that removes all the even numbers from a vector
  3. A function that returns a sorted copy, leaving the original alone
  1. &Vec<i32>. It only reads
  2. &mut Vec<i32>. It changes the caller's vector in place
  3. &Vec<i32> in, a new Vec<i32> out. The clone happens inside, once, because the job is defined as making a copy. Cloning at the call site would make two

Using &mut T as a parameter

&mut means the function can change the caller's data, and the caller sees it afterward.

fn main() {
    let mut message = String::from("Hello");
    modify_string(&mut message);
    println!("{}", message);  // "Hello!!!"
}

fn modify_string(text: &mut String) {
    text.push_str("!!!");
}

Three things to notice:

  1. message must be mut to begin with
  2. The caller writes &mut message
  3. Inside, text.push_str auto-dereferences. For plain assignment, *text = ...

Let's watch it in memory. (You can draw along on your sheets)

Step 4: after the call

Stack:                                     Heap:
┌───────────────────────┐
│ main()                │
│ └ message: String     │                 ┌─────┬─────┬─────┬─────┬─────┬─────┬─────┬─────┐
│    ├ ptr ─────────────┼────────────────▶│ 'H' │ 'e' │ 'l' │ 'l' │ 'o' │ '!' │ '!' │ '!' │
│    ├ len: 8           │                 └─────┴─────┴─────┴─────┴─────┴─────┴─────┴─────┘
│    └ cap: 10          │
└───────────────────────┘

modify_string's frame is gone, and the borrow ended with it. message is the only name left, and it owns the new, longer text.

Steps 1 to 4. Draw it once, then update it as we go.













Activity 25, Problem 1: draw what crosses the frame

See Problem 1 on Activity 25.

Two frames. main holds a (15 after the marked line) and b (5). process holds x and y, both arrows pointing back into main's frame. Nothing is on the heap. The data never moved; process only ever had the addresses.

Review of *: follow the arrow

Remember how raw pointers needed * to read, references did not (auto-dereferencing)?

Here's a recap of when that works and when we still need *

fn main() {
    let x = 42;
    let y = 10;
    let x_ref = &x;
    let y_ref = &y;

    let sum = *x_ref + *y_ref;      // follow both arrows, add the values
    println!("Sum: {}", sum);

    let sum2 = x_ref + y_ref;       // also fine: + is defined for references too
    println!("Sum: {}", sum2);

    println!("x_ref: {}", x_ref);   // println! follows the arrow for you
    println!("*x_ref: {}", *x_ref); // same thing, written out

    println!("{}", *x_ref > 5);     // comparisons need the *
    // println!("{}", x_ref > 5);   // uncomment: expected `&_`, found integer
}

When do you need it?

  • Comparisons on the value: *x_ref > 5, *x_ref == 10.
  • Assigning through a &mut: *r = 5

When it's optional (auto-dereferencing)

  • Math: x_ref + 1 and *x_ref + 1 are both fine
  • Displaying/printing like println! and format!
  • Method calls like .len(), or .push() or even .clone()

You are always safe writing the * yourself. If it wasn't needed, nothing breaks.

Two muts in one line

*r = value changes the data behind a mutable reference. But you might also want to change where the reference itself points. That takes its own mut.

fn main() {
    let mut x = 5;
    let mut y = &mut x;

    *y = 10;                      // change the value y points at
    println!("y is now: {}", y);
    println!("x is now: {}", x);  // 10

    let mut z = 6;
    y = &mut z;                   // point y at something else
    println!("y is now: {}", y);
}

The two assignments do different things:

  • *y = value changes what y points at
  • y = &mut other changes where y points

In practice: read, then write

Most real code separates its reading phase from its writing phase, and then the rules never bite.

fn main() {
    let mut scores = vec![85, 92, 78, 96, 88];

    let (total, average) = analyze(&scores);       // reader, borrow ends at return
    println!("Total: {}, Average: {:.1}", total, average);

    normalize(&mut scores);                         // writer, borrow ends at return
    println!("Normalized: {:?}", scores);
}

fn analyze(data: &Vec<i32>) -> (i32, f64) {
    let sum: i32 = data.iter().sum();
    (sum, sum as f64 / data.len() as f64)
}

fn normalize(data: &mut Vec<i32>) {
    let max = *data.iter().max().unwrap();
    for item in data.iter_mut() {
        *item = *item * 100 / max;
    }
}

A function's borrow ends when the function returns, unless it hands a reference back. So two calls in a row never conflict.

normalize has one new thing in it: iter_mut().

.iter() lends, .iter_mut() lends mutably

fn main() {
    let mut numbers = vec![1, 2, 3, 4, 5];

    for num in numbers.iter() {        // num: &i32, a reader
        println!("{}", num);
        // *num += 1;                   // error: cannot assign through a & reference
    }

    for num in numbers.iter_mut() {    // num: &mut i32, a writer
        *num += 10;                     // follow the arrow and change what is there
    }
    println!("{:?}", numbers);         // [11, 12, 13, 14, 15]

    let mut names = vec![String::from("Alice"), String::from("Bob")];
    for name in names.iter_mut() {     // name: &mut String
        name.push_str("!");            // a method, so no * needed
    }
    println!("{:?}", names);           // ["Alice!", "Bob!"]
}

Each loop borrows the whole vector for the length of the loop.

Reading & and * in a loop

for num in v.iter() gives you references, not values. There are two (and a half) ways to get the value out:

fn main() {
    let numbers = vec![10, 20, 30];


    for num_ref in numbers.iter() {    // num_ref: &i32
        let squared = *num_ref * *num_ref;    // deref by hand
        // let squared = num_ref * num_ref    // or auto-deref
        println!("{}", squared);
    }

    for &num in numbers.iter() {       // num: i32, copied out by the pattern
        let squared = num * num;
        println!("{}", squared);
    }

    let names = vec![String::from("Alice"), String::from("Bob")];
    for name in names.iter() {         // name: &String
        println!("{}", name.len());    // methods auto-deref
    }
    // for &name in names.iter() { }   // error: cannot move out of a reference
}

The & in a pattern says "match a reference, bind what it points to." That copies the value out, so it only works for Copy types. For a String, keep the reference and use it; or .clone() if you need your own.

Four ways to loop over a vector

LoopEach item isThe vector afterward
for x in v.iter()&Tuntouched
for x in &v&T, same thinguntouched
for x in v.iter_mut()&mut Tchanged in place
for x in vTmoved, or copied for a Copy type

.enumerate() works on any of them and adds the index: for (i, x) in v.iter_mut().enumerate() gives (usize, &mut T).

Lifetimes: when they can be inferred

Borrow checker rule 2: a reference must never outlive what it points at.

Sometimes the compiler can check lifetimes itself and error if the rule would be violated:

fn main() {
    let outer;    // declared here, set later
    {
        let inner = vec![1, 2, 3];
        outer = &inner;
        println!("Inside: {:?}", outer);
    }
    println!("Outside: {:?}", outer);
}

Lifetimes: when they CAN'T be inferred

longest hands back one of its two inputs. Whose lifetime does the result have to stay inside?

fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() { x } else { y }
}

fn main() {
    let a = String::from("long string");
    let b = String::from("short");
    println!("{}", longest(&a, &b));
}

The returned reference points at one of the inputs, and the compiler cannot tell which. So it cannot check rule 2 for the caller.

Reading explicit lifetimes

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

fn main() {
    let a = String::from("long string");
    let b = String::from("short");
    println!("{}", longest(&a, &b));
}

'a is pronounced "tick a". Read the signature as: "the result lives no longer than the shorter-lived of x and y."

  • <'a> declares a name for a lifetime, the way <T> would declare a type
  • &'a str on an input says "this is one of the references the result might point at"
  • &'a str on the output says "the result borrows from one of those"

It changes nothing about how long anything lives. It is a promise the compiler then checks: if the caller lets a or b die while the result is still in use, that is a rule 2 error.

Let's draw out the borrow checker's work here

Bracket a, b, and result. Does it compile?

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}

fn main() {
    let a = String::from("long string");
    let result;
    {
        let b = String::from("short");
        result = longest(&a, &b);
    }
    println!("{}", result);
}

'static, and what you actually have to do

One special lifetime is 'static which means "lives for the whole program."

let s: &'static str = "Hello world";   // a literal, stored in the program binary
fn greeting() -> &'static str { "Hello!" }   // nothing to borrow from: it is always there

String literals are 'static, which is why we draw them in the program binary and not on the heap.

In practice, you will rarely write a lifetime. When you do need one, the compiler says so and suggests the annotation. Your job would be to read it:

  1. <'a> means the function returns a borrow of one of its inputs
  2. 'static means the data is there for the whole program
  3. If a snippet on an exam has an 'a or 'static in it, that is what it means. But I'm not going to ask you to reason about it directly.

Activity 25

See Activity 25. Diagrams and trade-offs. Problem 1 is done, so start at Problem 2.