Every Rust learner hits the same wall, usually in the first week. You write something that would be perfectly normal in JavaScript, and the compiler refuses with a message about a "moved value" or a "borrow". You add a .clone() to make it go away, it compiles, and you move on slightly unsettled.
This part is about that wall. Ownership is the idea that makes Rust different from every language you've used, and it's the reason Rust programs can be memory safe without a garbage collector. Once it clicks, most of the compiler errors you'll see for the rest of the series stop being mysterious. They become the compiler pointing at a real question about your code: who is responsible for this value, and who is allowed to change it right now?
In part 2 I waved several things away and promised to explain them here: why first + &second used up first, what the & means, why a function taking &str is better than one taking String, and what 'static was doing in a return type. All of those are ownership. We'll take it slowly, with the actual compiler errors from Rust 1.100.0, and the JavaScript behaviour for comparison at each step.
The problem ownership solves
Every program has to answer a question about memory: when can a piece of data be thrown away?
In JavaScript you never think about it. You create objects, pass them around, and at some point a garbage collector notices that nothing refers to an object any more and frees it. That's very convenient. The costs are that the collector runs while your program does, it uses extra memory to do its job, and it can pause things at moments you don't control. For a web page that's almost always fine. For a server handling thousands of requests a second, those pauses and that memory show up in your latency graphs and your hosting bill.
In C and C++ you free memory yourself. That's fast, and also the source of decades of security bugs: freeing something twice, using it after it's freed, or never freeing it. Microsoft and Google have both reported that around 70% of their serious security bugs are memory safety problems of this kind.
Rust takes a third route. The compiler tracks, at compile time, which variable is responsible for each piece of data. When that variable goes away, the data is freed, automatically and immediately. There's no garbage collector running in the background and no manual free. The rules that make this work are the ownership rules, and the part of the compiler that enforces them is called the borrow checker.
The trade is that you have to write code the borrow checker can verify. Most of the time that's code you'd consider well structured anyway. Some of the time it means rearranging things in a way that feels unnecessary at first. This part is about building the instincts for both.
The three rules
The Rust book states ownership as three rules:
- Each value in Rust has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
"Dropped" means cleaned up: its memory is freed, and if it holds a file handle or a network connection, that's closed too. Let's watch it happen.
Watching values get dropped
Rust lets a type run code when it's dropped, through the Drop trait. We haven't covered traits yet (that's part 7), so treat this as a small instrument: a type that prints a line when it's cleaned up.
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn main() {
let _outer = Noisy("outer");
{
let _inner = Noisy("inner");
println!("end of inner block");
}
let moved = Noisy("moved");
take(moved);
println!("end of main");
}
fn take(n: Noisy) {
println!("take got {}", n.0);
}
end of inner block
dropping inner
take got moved
dropping moved
end of main
dropping outer
Read that output slowly, because it's the whole model in six lines.
_inner is created inside a block, so it's dropped the moment that block's closing brace is reached. _outer lives until the end of main, so it's dropped last. The interesting one is moved. It was created in main, but it was dropped inside take, before "end of main" printed. Passing it to take handed over ownership. take became the owner, and when take returned, its parameter went out of scope and the value was dropped there.
No garbage collector decided any of that. The compiler knew exactly where each value's owner ends, and inserted the cleanup at that point.
Moves
Here's the first thing that surprises JavaScript developers:
fn main() {
let a = String::from("hello");
let b = a;
println!("{a} {b}");
}
error[E0382]: borrow of moved value: `a`
--> src/bin/e_moved.rs:4:16
|
2 | let a = String::from("hello");
| - move occurs because `a` has type `String`, which does not implement the `Copy` trait
3 | let b = a;
| - value moved here
4 | println!("{a} {b}");
| ^ value borrowed here after move
|
help: consider cloning the value if the performance cost is acceptable
|
3 | let b = a.clone();
| ++++++++
In JavaScript, const b = a with an object gives you two variables pointing at the same object. Both work. In Rust, let b = a moves the String from a to b. After that line, a is no longer usable. The string wasn't copied, and it isn't shared. It changed owners.
Why? Remember rule 2: one owner at a time. If both a and b owned the same string, then when both went out of scope, the string would be freed twice. That's one of the classic C bugs. Rust prevents it by making assignment a transfer. There's always exactly one variable responsible for freeing the string.
It helps to know what a String actually is in memory. The variable itself holds three numbers: a pointer to the text on the heap, the length, and the capacity. The text lives on the heap. A move copies those three numbers into the new variable and marks the old one as unusable. The heap text doesn't move at all. That's why moves are cheap: a move is never a deep copy, however large the string.
The compiler error is worth reading line by line, because every borrow checker error has the same shape. It points at three places: where the value was created ("move occurs because..."), where ownership went ("value moved here"), and where you tried to use it after ("value borrowed here after move"). When you hit an ownership error, find those three points and the problem is usually obvious.
Clone and Copy
The compiler's suggestion was a.clone(). Here it is working:
let original = String::from("hello");
let copy = original.clone();
println!("original = {original}, copy = {copy}");
original = hello, copy = hello
.clone() makes a deep copy: new heap memory, the text copied in. Now there are two separate strings with two separate owners, and no conflict. It's the equivalent of structuredClone(obj) in JavaScript.
Cloning is always correct, and it's sometimes the right answer. But it costs an allocation and a copy, and when you find yourself adding .clone() just to silence the compiler, it's often a sign that borrowing (next section) is what you wanted. In beginner code I'd say: clone freely when you're learning, and come back later to see which clones you can remove.
Now try the same thing with a number:
let x = 5;
let y = x;
println!("x = {x}, y = {y}");
x = 5, y = 5
No error. Integers, floats, bool, char, and tuples or arrays made only of those, implement the Copy trait. For these types, assignment copies the value instead of moving it. They're small, they live entirely on the stack, and copying them is as cheap as moving them, so Rust doesn't bother with ownership transfer. The error message said this directly: "move occurs because a has type String, which does not implement the Copy trait".
A useful rule of thumb: if a type owns something on the heap (String, Vec, HashMap, Box), it moves. If it's a plain number-like value, it copies.
Moving into functions
Passing a value to a function is the same as assigning it. It moves:
fn shout(text: String) -> String {
text.to_uppercase()
}
fn main() {
let name = String::from("ferris");
let loud = shout(name);
println!("{name} {loud}");
}
error[E0382]: borrow of moved value: `name`
--> src/bin/e_fnmoved.rs:8:16
|
6 | let name = String::from("ferris");
| ---- move occurs because `name` has type `String`, which does not implement the `Copy` trait
7 | let loud = shout(name);
| ---- value moved here
8 | println!("{name} {loud}");
| ^^^^ value borrowed here after move
|
note: consider changing this parameter type in function `shout` to borrow instead if owning the value isn't necessary
--> src/bin/e_fnmoved.rs:1:16
|
1 | fn shout(text: String) -> String {
| ----- ^^^^^^ this parameter takes ownership of the value
| |
| in this function
shout takes a String, so calling it gives away name. After the call, name is gone. And notice the compiler's note: "consider changing this parameter type in function shout to borrow instead if owning the value isn't necessary". It's pointing at the real fix. shout only reads the text to produce a new uppercase string. It never needed to own it.
This is also what happened with first + &second in part 2. The + operator on strings takes its left side by value, so first was moved into the result. It reuses first's heap buffer, appends to it, and hands it back as the new string, which is efficient, and also why first can't be used afterwards.
Loops move too, which catches everyone at least once:
let names = vec![String::from("ana"), String::from("bo")];
for name in names {
println!("{name}");
}
println!("{} names", names.len());
error[E0382]: borrow of moved value: `names`
--> src/bin/e_loopmove.rs:6:26
|
2 | let names = vec![String::from("ana"), String::from("bo")];
| ----- move occurs because `names` has type `Vec<String>`, which does not implement the `Copy` trait
3 | for name in names {
| ----- `names` moved due to this implicit call to `.into_iter()`
...
6 | println!("{} names", names.len());
| ^^^^^ value borrowed here after move
|
help: consider iterating over a slice of the `Vec<String>`'s content to avoid moving into the `for` loop
|
3 | for name in &names {
| +
for name in names takes ownership of the vector and hands you each string by value. When the loop ends, the vector is gone. If you want to keep it, loop over &names instead, which brings us to borrowing.
Borrowing
Moving ownership around would be exhausting if it were the only option. Imagine having to return every argument from every function so the caller could have it back. Rust's answer is references, also called borrows. A reference lets you use a value without taking ownership of it.
fn length(text: &String) -> usize {
text.len()
}
fn main() {
let name = String::from("ferris");
let n = length(&name);
println!("{name} has {n} letters");
let loud = shout(name);
println!("{loud}");
}
ferris has 6 letters
FERRIS
&name creates a reference to name. length takes &String, a reference to a String. It can read the string, but it doesn't own it, so when length returns, nothing is dropped. name is still valid on the next line. Then we call shout(name) without the &, which moves it, and that's fine too, because we don't use name again.
The analogy I find works best is lending a book. Ownership is having the book. A move is giving it away. A borrow is lending it: the other person can read it, but they have to give it back, and while they have it you can't throw it out.
Mutable borrows
A plain & reference is read-only. To let a function change something you own, lend it with &mut:
fn add_exclamation(text: &mut String) {
text.push('!');
}
fn main() {
let mut greeting = String::from("hello");
add_exclamation(&mut greeting);
add_exclamation(&mut greeting);
println!("{greeting}");
}
hello!!
Three things have to line up: the variable is let mut, the borrow is &mut greeting, and the parameter type is &mut String. Forget the last one and you get a very precise error:
error[E0596]: cannot borrow `*text` as mutable, as it is behind a `&` reference
--> src/bin/e_notmut.rs:2:5
|
2 | text.push('!');
| ^^^^ `text` is a `&` reference, so it cannot be borrowed as mutable
|
help: consider changing this to be a mutable reference
|
1 | fn add_exclamation(text: &mut String) {
| +++
This has a nice side effect for reading code. In JavaScript, when you pass an object to a function, you can't tell from the call site whether the function will modify it. In Rust you can. add_exclamation(&mut greeting) says "this will change greeting" right there in the call. length(&name) says it won't.
The borrowing rules
Here's the heart of it. At any given moment, for any value, you can have either:
- any number of shared references (
&T), or - exactly one mutable reference (
&mut T),
but not both at once. Many readers, or one writer.
let r1 = &greeting;
let r2 = &greeting;
println!("two readers: {r1} and {r2}");
let r3 = &mut greeting;
r3.push_str(" world");
println!("after the readers are done: {greeting}");
two readers: hello!! and hello!!
after the readers are done: hello!! world
Two shared references at once: fine. Then a mutable one: also fine, because by that point r1 and r2 are never used again. The compiler tracks where each reference is last used, rather than where its variable's scope ends. This is called non-lexical lifetimes, and it's why a lot of code that looks like it breaks the rule actually compiles.
Here's what breaking it looks like. Two mutable borrows at once:
let mut list = vec![1, 2, 3];
let a = &mut list;
let b = &mut list;
a.push(4);
b.push(5);
error[E0499]: cannot borrow `list` as mutable more than once at a time
--> src/bin/e_twomut.rs:4:13
|
3 | let a = &mut list;
| --------- first mutable borrow occurs here
4 | let b = &mut list;
| ^^^^^^^^^ second mutable borrow occurs here
5 | a.push(4);
| - first borrow later used here
And the one that matters most in practice, modifying something while a reference into it is still alive:
let mut list = vec![1, 2, 3];
let first = &list[0];
list.push(4);
println!("first is {first}");
error[E0502]: cannot borrow `list` as mutable because it is also borrowed as immutable
--> src/bin/e_readwrite.rs:4:5
|
3 | let first = &list[0];
| ---- immutable borrow occurs here
4 | list.push(4);
| ^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("first is {first}");
| ----- immutable borrow later used here
This one looks overly strict. We're only reading the first element and adding to the end. What could go wrong?
Here's what. A Vec stores its elements in one block of heap memory. When you push and the block is full, the vector allocates a bigger block, copies everything over, and frees the old one. first points into the old block. After the push, it would be pointing at freed memory. In C++ this exact bug is common enough to have a name, iterator invalidation. Rust's rule doesn't need to know anything about how Vec grows. "No writing while someone is reading" rules out the whole category.
Why "many readers or one writer" is the right rule
This rule prevents something JavaScript developers have definitely debugged: a value changing underneath you.
let mut cart = vec!["apple"];
let alias = &mut cart;
alias.push("bread");
println!("cart: {:?}", cart);
let snapshot = cart.clone();
cart.push("milk");
println!("cart: {:?}, snapshot: {:?}", cart, snapshot);
cart: ["apple", "bread"]
cart: ["apple", "bread", "milk"], snapshot: ["apple", "bread"]
In JavaScript, const alias = cart gives you a second name for the same array, and both can change it at any time, from anywhere, including from a callback that runs later. That's the source of bugs like a React state object being mutated in place, or a config object changed by one module and read by another. In Rust, while alias is a live mutable reference, nothing else can touch cart. Once alias is done, cart is yours again. If you want an independent copy that won't see future changes, you say so with .clone().
The same rule is what makes concurrent Rust safe. A data race needs two threads accessing the same data with at least one writing. "Many readers or one writer" is exactly the condition that rules data races out, and Rust enforces it at compile time. We'll lean on this heavily in part 9 when we get to async, and again in the Axum parts when request handlers share state.
Slices: borrowing part of something
A slice is a reference to a contiguous part of a collection. You've already used one: &str is a string slice.
fn first_word(text: &str) -> &str {
text.split_whitespace().next().unwrap_or("")
}
fn total(numbers: &[i32]) -> i32 {
let mut sum = 0;
for n in numbers {
sum += n;
}
sum
}
fn main() {
let sentence = String::from("borrow checker friend");
let word = first_word(&sentence);
println!("first word: {word}");
let scores = vec![10, 20, 30, 40];
println!("all: {}", total(&scores));
println!("middle two: {}", total(&scores[1..3]));
}
first word: borrow
all: 100
middle two: 50
first_word returns a &str that points into sentence. No new string is created. It's just a pointer and a length describing where "borrow" sits inside the original text. That's why slicing is cheap, and why first_word can't outlive the String it points into.
&[i32] is the same idea for any list: a slice of i32 values. total accepts &scores, a borrowed whole vector, or &scores[1..3], a borrowed part of it. Rust converts &Vec<i32> to &[i32] automatically, the same way it converts &String to &str.
This is why I said in part 2 that functions should take &str rather than &String or String. A &str parameter accepts string literals, borrowed Strings and slices of either. A &[T] parameter likewise accepts arrays, vectors and parts of both. Taking the most general borrowed form makes a function easier to call and costs nothing.
No dangling references
In C you can return a pointer to a local variable, and the caller gets a pointer to memory that's already been reused. Try it in Rust:
fn make() -> &String {
let s = String::from("temporary");
&s
}
error[E0106]: missing lifetime specifier
--> src/bin/e_dangle.rs:1:14
|
1 | fn make() -> &String {
| ^ expected named lifetime parameter
|
= help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
|
1 | fn make() -> &'static String {
| +++++++
help: instead, you are more likely to want to return an owned value
|
1 - fn make() -> &String {
1 + fn make() -> String {
|
The help text is excellent: "this function's return type contains a borrowed value, but there is no value for it to be borrowed from". A function with no parameters can only return a reference to something that lives forever. s is dropped when make returns, so a reference to it would dangle.
The fix is the compiler's second suggestion: return the String itself. Ownership moves out to the caller, nothing is dropped, nothing dangles. When a function creates a value, return it owned. That's a rule you'll use constantly.
Lifetimes, gently
That error mentioned a "lifetime specifier", and you saw 'static in part 2. Lifetimes are the part of ownership people find most intimidating, mostly because of the syntax. The idea is simpler than it looks.
Every reference is valid for some stretch of the program: from when it's created until the thing it points at is dropped or changed. That stretch is its lifetime. The compiler checks that no reference is used outside its lifetime. Almost always it works this out without any help from you.
It needs help when a function takes several references and returns one, because from the signature alone it can't tell which input the output points into:
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
'a is a lifetime parameter, a name for "some stretch of the program". The signature says: given two string slices that are both valid for at least 'a, the returned slice is also valid for 'a. In practice that means the result can only be used while both inputs are still alive.
You aren't telling the compiler how long anything lives. You can't change that with annotations. You're describing the relationship between inputs and outputs so the compiler can check the caller. Here's a caller that respects it:
let first = String::from("axum");
let winner;
{
let second = String::from("tokio");
winner = longer(&first, &second);
println!("longer: {winner}");
}
longer: tokio
And here's the same code with the println! moved one line down, outside the block:
error[E0597]: `second` does not live long enough
--> src/bin/e_lifetime.rs:10:33
|
9 | let second = String::from("tokio");
| ------ binding `second` declared here
10 | winner = longer(&first, &second);
| ^^^^^^^ borrowed value does not live long enough
11 | }
| - `second` dropped here while still borrowed
12 | println!("longer: {winner}");
| ------ borrow later used here
winner might point into second, and second was dropped at the closing brace. In this run it actually would have, since "tokio" is longer. The compiler doesn't run your code to find out. It goes by the signature, and the signature says the result might come from either input.
When you need to write lifetimes
Rarely, at this stage. The compiler applies a few rules, called lifetime elision, that cover most functions:
- If there's exactly one reference input, the output borrows from it. That's why
first_word(text: &str) -> &strneeded no annotation. - If it's a method that takes
&self, the output borrows fromself. - Otherwise, you have to write them.
'static is the one named lifetime built into the language. It means "valid for the entire run of the program". String literals are &'static str because their text is baked into the compiled binary. That's what part 2's describe function was returning.
If you're unsure, start by returning owned values (String, Vec<T>) and taking borrowed ones (&str, &[T]). That combination needs no lifetime annotations, and it's what most application code does. Lifetimes show up more in library code and in structs that hold references, which we'll avoid until it's worth it.
A field guide to borrow checker errors
Here are the errors you've now seen, what each means, and what usually fixes it. Keep this list nearby for the next few weeks.
| Error | What it means | Usual fix |
|---|---|---|
| E0382 use of moved value | You gave a value away and then used it | Borrow with & instead of moving, or .clone() if you need two copies |
| E0499 more than one mutable borrow | Two writers at once | Finish with one &mut before making the next, often by reordering lines |
| E0502 mutable and immutable borrow | Writing while a reader is alive | Use the reader first, or copy the value out (let first = list[0];) |
| E0596 cannot borrow as mutable | Changing through a & reference |
Make the parameter &mut T and the variable let mut |
| E0597 does not live long enough | A reference outlives what it points to | Move the owner to an outer scope, or return an owned value |
| E0106 missing lifetime specifier | Returning a reference with no clear source | Return an owned value, or add lifetime parameters |
| E0515 cannot return reference to local | Returning a borrow of something about to be dropped | Return the owned value instead |
One fix from that table deserves a closer look. In the E0502 example, first was a reference into the vector. If you write let first = list[0]; without the &, you get a copy of the integer, because i32 is Copy, and the push compiles fine. Many borrow checker errors disappear when you realise you wanted a copy of a small value rather than a reference to it.
How this compares to JavaScript, all together
| Situation | JavaScript | Rust |
|---|---|---|
b = a with an object |
Both names share one object | Ownership moves to b, a is unusable |
b = a with a number |
Copied | Copied (numbers are Copy) |
| Independent copy | structuredClone(a) |
a.clone() |
| Pass to a function | Function gets a shared reference | Moves, unless you pass &a or &mut a |
| Function modifies its argument | Invisible at the call site | Visible: f(&mut a) |
| Two parts of code mutating one object | Allowed, often the bug | Compile error |
| Freeing memory | Garbage collector, eventually | When the owner goes out of scope, immediately |
| Closing a file or connection | finally, or using in newer JS |
Automatic on drop |
That last row is underrated. Because cleanup is tied to scope, Rust doesn't need finally blocks or try-with-resources for files, locks or database connections. When the variable holding a file goes out of scope, the file closes. When a lock guard goes out of scope, the lock is released. This pattern is called RAII, and it's quietly why Rust web servers don't leak connections.
Back to wordfreq
The word counter has a piece of code that I promised would make sense after this part:
let mut sorted: Vec<(&String, &usize)> = counts.iter().collect();
sorted.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
for (rank, (word, count)) in sorted.iter().take(top).enumerate() {
let bar = "#".repeat(**count);
Now you can read it. counts.iter() borrows the map and yields a pair of references for each entry: &String for the key and &usize for the count. sorted is a vector of those borrowed pairs. Nothing was copied out of the map. Then sorted.iter() borrows sorted, so each item in the loop is a reference to a pair of references, which is why count needed ** to reach the number.
That's correct and efficient, but it reads badly. Let's move the sorting into its own function and make it return something easier to use:
fn top_words(counts: &HashMap<String, usize>, n: usize) -> Vec<(&str, usize)> {
let mut pairs: Vec<(&str, usize)> = counts
.iter()
.map(|(word, count)| (word.as_str(), *count))
.collect();
pairs.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
pairs.truncate(n);
pairs
}
Each pair is now (&str, usize): the word is borrowed from the map, because copying every word would be wasteful, and the count is copied out, because a usize is Copy and copying it is free. *count dereferences the &usize to get the number. pairs.truncate(n) keeps the first n.
Look at the signature. It takes one reference, &HashMap, and returns references inside a Vec. By elision rule 1, the returned &str values borrow from counts. No lifetime annotations needed, and the compiler will make sure the map outlives the result.
The loop in main becomes:
for (rank, (word, count)) in top_words(&counts, top).into_iter().enumerate() {
let bar = "#".repeat(count);
.into_iter() consumes the vector, which is fine because we don't need it afterwards, and hands out each pair by value, so count is a plain usize. No more **.
A test for the new function:
#[test]
fn top_words_sorts_by_count_then_alphabet() {
let counts = count_words("b a b c a b");
assert_eq!(top_words(&counts, 2), vec![("b", 3), ("a", 2)]);
}
running 4 tests
....
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
And the output is unchanged, which is the point of a refactor:
1. is 4 ####
2. the 4 ####
3. cargo 3 ###
Breaking it on purpose
Now let's see the borrow checker protect us. Say you want a helper that reads a file and returns its top words in one call:
fn top_of_file(path: &str, n: usize) -> Vec<(&str, usize)> {
let text = fs::read_to_string(path).unwrap();
let counts = count_words(&text);
top_words(&counts, n)
}
error[E0515]: cannot return value referencing local variable `counts`
--> src/main.rs:68:5
|
68 | top_words(&counts, n)
| ^^^^^^^^^^-------^^^^
| | |
| | `counts` is borrowed here
| returns a value referencing data owned by the current function
The words in the returned vector point into counts, and counts is dropped when top_of_file returns. In JavaScript this would just work, because the garbage collector would keep the map alive as long as anything pointed into it. In C it would compile and return garbage. Rust refuses, and tells you exactly why.
The fix is to return owned data, Vec<(String, usize)>, by converting each word with word.to_string(). That costs one small allocation per returned word, and for the top five words of a file that's nothing. This is the trade-off you'll make again and again: borrow when the owner clearly outlives the use, own when it doesn't.
When you get stuck
Some practical advice, from the usual experience of learning this:
- Read the whole error. Rust's borrow checker errors point at the creation, the move or borrow, and the conflicting use. Find all three in your code.
- Try the compiler's suggestion. It's right more often than you'd expect, especially the
&and&mutones. - Clone and move on. A
.clone()in a learning project is not a failure. Get it working, then see if you can remove it. - Return owned values from functions that create data. Take borrowed values in functions that only read.
- If you're fighting the compiler for more than twenty minutes, the structure is probably the issue. Split the function, shorten how long a reference lives, or copy a small value out instead of holding a reference to it.
There are also tools for genuinely shared ownership: Rc and Arc for multiple owners, RefCell and Mutex for controlled mutation through shared references. You'll meet Arc and Mutex properly when we share state between Axum handlers in part 11. For now, the plain rules are enough, and learning to work within them first makes those tools much easier to use correctly.
Exercises
- Write
fn longest_line(text: &str) -> &strthat returns the longest line. Does it need a lifetime annotation? Why or why not? - Write
fn make_greeting(name: &str) -> String. Now change the return type to&strand read the error. Change it back. - Change
top_of_fileto returnVec<(String, usize)>and make it compile. - Write a function that takes
&mut Vec<i32>and removes every negative number. Call it twice on the same vector. Then try holding a reference to the first element across the call and read the error. - Add a
Noisyvalue to thewordfreqmain function and check where it gets dropped when the program exits early withprocess::exit(1). Look up whatprocess::exitsays about destructors in the standard library docs. What does that mean for cleanup?
Next up: structs, enums and pattern matching
So far all our data has been numbers, strings, tuples and collections. In part 4 we start defining our own types. Structs group related fields, like a TypeScript interface with data in it. Enums go much further than TypeScript's enums: each variant can carry its own data, which makes them closer to TypeScript's discriminated unions, and match checks you've handled every case. Together they let you model data so that invalid states can't be written down, which is one of the most useful habits Rust will give you.
The ownership rules carry straight over. A struct owns its fields, a struct holding a String moves, and methods borrow self with &self or &mut self. You now know what all of those mean.