Ownership and borrowing
Moves, references and slices, taught on the text of a log file, with the three borrow checker errors you are most likely to meet first.
- lesson
- 02 of 08
- read
- 14 min
Rust frees memory without a garbage collector and without explicit free calls. It does this by tracking, at compile time, which variable owns each value and how long every reference to that value is in use. This lesson works through the rules on tally’s own data, the text of a log file, by provoking the compiler errors a newcomer meets first and fixing each one. At the end the program reads several files and lists the distinct client addresses.
One owner
fs::read_to_string returns a String: a heap buffer of UTF-8 bytes together with its length and capacity. The variable contents owns that buffer, and when contents goes out of scope the buffer is freed. Move the counting loop from lesson 1 into a function that takes the text as an argument:
use std::env;
use std::fs;
fn count_requests(text: String) -> usize {
let mut count = 0;
for line in text.lines() {
if !line.is_empty() {
count += 1;
}
}
count
}
fn main() {
let path = env::args().nth(1).expect("usage: tally <file>");
let contents = fs::read_to_string(&path).expect("could not read file");
let count = count_requests(contents);
println!("{path}: {count} requests in {} bytes", contents.len());
}A function’s last expression, written without a semicolon, is its return value. That is what the bare count at the end of count_requests does.
error[E0382]: borrow of moved value: `contents`
--> src/main.rs:19:54
|
16 | let contents = fs::read_to_string(&path).expect("could not read file");
| -------- move occurs because `contents` has type `String`, which does not implement the `Copy` trait
17 |
18 | let count = count_requests(contents);
| -------- value moved here
19 | println!("{path}: {count} requests in {} bytes", contents.len());
| ^^^^^^^^ value borrowed here after move
|
note: consider changing this parameter type in function `count_requests` to borrow instead if owning the value isn't necessary
--> src/main.rs:4:25
|
4 | fn count_requests(text: String) -> usize {
| -------------- ^^^^^^ this parameter takes ownership of the value
| |
| in this function
help: consider cloning the value if the performance cost is acceptable
|
18 | let count = count_requests(contents.clone());
| ++++++++
For more information about this error, try `rustc --explain E0382`.Passing contents to a parameter of type String moves it. Ownership transfers to text, and the buffer is freed when count_requests returns. The name contents is dead from the call onwards. Only the pointer, length and capacity are copied, never the bytes. In JavaScript, Python or Go both names would refer to one object and the garbage collector would keep it alive. In Rust a value has exactly one owner at a time, and the compiler keeps track of which.
The first label mentions Copy. Types such as integers and bool implement that trait and are duplicated on assignment, which is why count never caused this problem.
The compiler offers two ways out. Its help suggests contents.clone(), which duplicates the whole buffer so that each side owns one. Its note suggests that the function borrow the text instead, and that is the right fix here: counting lines requires reading the text, not owning it.
Borrowing
Two lines change:
fn count_requests(text: &str) -> usize { let count = count_requests(&contents);&contents creates a reference: a pointer that lets count_requests read the string while main stays the owner.
cargo run -q -- access.logaccess.log: 18 requests in 1827 bytes(-q silences Cargo’s own progress lines.)
The parameter type is &str and not &String. A &str is a string slice: a pointer and a length, viewing UTF-8 bytes that something else owns. A &String converts to &str automatically, and a string literal already is one, so a function that takes &str accepts both.
| Type | Owns its bytes | Use it for |
|---|---|---|
String |
yes | text you build, change or keep |
&str |
no | text you only read |
The call fs::read_to_string(&path) in lesson 1 was the same idea: lend path to the function so that println! could still use it afterwards.
Slices point into the original
In an access log, the client address is everything before the first space:
fn client_addr(line: &str) -> &str {
let end = line.find(' ').unwrap_or(line.len());
&line[..end]
}find returns the byte index of the first space as an Option<usize>, and unwrap_or supplies the full length when there is none. &line[..end] is the slice of line from its start up to end. No bytes are copied: the returned &str points into the same buffer as the argument. contents.lines() works the same way and yields slices of contents. The file, each line and each address are one allocation seen through narrower and narrower views.
That is cheap, and it comes with a condition. A view is valid only while the buffer it points into is alive.
A reference that outlives its data
Extend the program to several files and collect every address in a list. count_requests is no longer called, so delete it, and replace main with this:
fn main() {
let mut clients: Vec<&str> = Vec::new();
for path in env::args().skip(1) {
let contents = fs::read_to_string(&path).expect("could not read file");
for line in contents.lines() {
if !line.is_empty() {
clients.push(client_addr(line));
}
}
}
println!("{} requests", clients.len());
}Vec<T> is a growable array. env::args().skip(1) iterates over all arguments after the program name.
error[E0597]: `contents` does not live long enough
--> src/main.rs:14:21
|
10 | let mut clients: Vec<&str> = Vec::new();
| ----------- variable `clients` declared here
...
13 | let contents = fs::read_to_string(&path).expect("could not read file");
| -------- binding `contents` declared here
14 | for line in contents.lines() {
| ^^^^^^^^ borrowed value does not live long enough
...
19 | }
| - `contents` dropped here while still borrowed
20 |
21 | println!("{} requests", clients.len());
| ------- borrow later used here
|
= note: `clients` is a collection that stores borrowed references, but `contents` does not live long enough to be stored in it
= help: buffer reuse with borrowed references requires unsafe code or restructuring
For more information about this error, try `rustc --explain E0597`.The labels tell the story in order. contents is declared inside the loop body, so it is dropped at the closing brace on line 19, once per iteration. clients is declared outside the loop and still holds slices pointing into that buffer when line 21 uses it. The equivalent C compiles and reads freed memory. The borrow checker rejects it.
There are two ways to fix this. One is to keep every file’s text alive for as long as clients, by reading all files into a Vec<String> before the loop that collects addresses. The other is to store owned copies: a Vec<String> filled with client_addr(line).to_string(). A copy costs one allocation per stored address and cuts the tie between the list and the file buffers. tally will keep a few facts from each line and throw the rest away, so it takes the second route. The working rule: borrow what you only look at, own what you keep.
One writer or many readers
A list with every address repeated is less useful than a list of distinct ones. This function adds an address unless the list already has it:
fn remember(seen: &mut Vec<String>, addr: &str) {
for known in seen.iter() {
if known == addr {
return;
}
}
seen.push(addr.to_string());
}&mut is a mutable reference: permission to change a value that someone else owns. The caller has to write remember(&mut clients, ...), so the mutation is visible at the call site.
A first draft of this function might have pushed from inside the loop:
fn remember(seen: &mut Vec<String>, addr: &str) {
for known in seen.iter() {
if known != addr {
seen.push(addr.to_string());
}
}
}The logic is wrong, and the compiler refuses the code before that matters:
error[E0502]: cannot borrow `*seen` as mutable because it is also borrowed as immutable
--> src/main.rs:12:13
|
10 | for known in seen.iter() {
| - -----------
| | |
| | immutable borrow occurs here
| _____| immutable borrow later used here
| |
11 | | if known != addr {
12 | | seen.push(addr.to_string());
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
13 | | }
14 | | }
| |_____- this for loop borrows `*seen` immutably, preventing mutation within its body
|
= help: consider using an index-based loop instead, or collecting modifications into a separate collection
For more information about this error, try `rustc --explain E0502`.The rule behind the message: at any point, a value may have any number of shared references (&T) or exactly one mutable reference (&mut T), never both. The loop holds a shared borrow of seen for as long as it iterates, and push needs an exclusive one. The reason is concrete. push may move the vector’s contents to a larger buffer, which would leave the iterator pointing at freed memory. Other languages document this as “do not modify a collection while iterating over it”. Rust turns it into a compile error. In the correct version the loop has ended, and its borrow with it, before push runs.
The complete program:
use std::env;
use std::fs;
fn client_addr(line: &str) -> &str {
let end = line.find(' ').unwrap_or(line.len());
&line[..end]
}
fn remember(seen: &mut Vec<String>, addr: &str) {
for known in seen.iter() {
if known == addr {
return;
}
}
seen.push(addr.to_string());
}
fn main() {
let mut requests = 0;
let mut clients: Vec<String> = Vec::new();
for path in env::args().skip(1) {
let contents = fs::read_to_string(&path).expect("could not read file");
for line in contents.lines() {
if line.is_empty() {
continue;
}
requests += 1;
remember(&mut clients, client_addr(line));
}
}
println!("{requests} requests from {} clients", clients.len());
for addr in &clients {
println!(" {addr}");
}
}cargo run -q -- access.log18 requests from 5 clients
203.0.113.7
198.51.100.23
192.0.2.44
2001:db8::1f
192.0.2.201Scanning a vector for every line gets slow as the number of distinct addresses grows; lesson 5 replaces the list with a hash map. Before that, the next lesson gives a parsed line a type of its own.
Exercises
- Write
fn request_line(line: &str) -> &strthat returns the text between the first two double quotes, or an empty string when the line has none.line.split('"').nth(1)gets you most of the way. Print it for every line: the first line of output for the sample file should beGET / HTTP/1.1, and the eighth should be empty. - Change
rememberto return aboolthat istruewhen the address was new, and use it to print each address at the moment it is first seen, not at the end. The addresses should appear in the same order as before. - Make the rejected
Vec<&str>version compile without copying any address: read every file into aVec<String>first, then fillclientsin a second loop over that vector. Withaccess.loggiven twice, the program should print36 requests. Work out why the borrow checker accepts this order and rejected the other.