The Programming Shortcut: Rust
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about ownership and borrowing, enforced by the compiler.
Rust is a language that keeps track of who is responsible for every value in your program, so that you don’t have to.
That sounds like a small thing. It isn’t. Every program that builds text, grows a list or reads a file is quietly borrowing memory from the computer, and somebody has to give it back at the right moment. Not too early, not twice, not never. Most languages answer that question for you while the program runs, and charge a little speed for it. A few hand the job to you and wish you luck. Rust answers it before the program runs, by reading your code and checking a handful of rules.
You already follow those rules in your head, most of the time, without names for them. Rust gives them names, writes them down, and checks every one. And when it refuses your program, it tells you which rule you broke, where, and usually what to do about it. Rust grew up among people writing a web browser, where a memory mistake is a crash at best and a security hole at worst. You get the benefit of their strictness for free, with a compiler that behaves like a patient teacher.
You already know half of it
Here is what carries over. Everything on the left you already have in some form.
| What you know | lux | Rust |
|---|---|---|
| a name that holds still | let | let |
| a name that can change | var | let mut |
| a function | func shout(text: string) -> string | fn shout(text: &str) -> String |
| a record | struct | struct |
| a list that grows | [int] | Vec<i64> |
| text | string | String when you own it, &str when you borrow it |
| a value that might be missing | Option<int>: some(x) or none | Option<i64>: Some(x) or None |
| an error you expect | Result<int, string>: ok(x) or err(e) | Result<i64, String>: Ok(x) or Err(e) |
| a value that is one of several shapes | enum | enum |
| covering every case | match | match |
Look at the text row and the function row. That & and the two kinds of text are
where this article lives. Nearly everything else is the same idea with a different
spelling.
If you have lux programs lying around, you have a shortcut nobody else does. Run this on one of them:
lux convert rust yours.lux > main.rs
It prints your program in Rust. Read it with one question in mind: where did all
those .clone() calls come from? By the end of this article you’ll know, and you’ll
know why Rust written by hand mostly doesn’t need them.
Cargo, and a compiler that talks back
You need one tool: cargo, which creates Rust projects, builds them and runs them.
It comes with Rust. On Linux or macOS, one command installs both:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
On Windows, or if you’d like to read before you pipe a script into your shell, the install page has the details.
Now make a project and run it:
cargo new ownership
cd ownership
cargo run
Cargo builds a tiny program it wrote for you and runs it, and you see
Hello, world!. The program lives in src/main.rs. From now on, you edit
src/main.rs, then cargo run. Every Rust example in this article is a whole
program you can paste over that file and run.
The other half of the job is reading what the compiler says when it refuses. Rust’s
error messages are long, and that’s a kindness. Each one has a code like E0382, a
picture of your code with arrows pointing at the lines involved, and often a help:
line with a suggested fix. Read them top to bottom, the way you’d read a note from a
colleague. You’ll be doing a lot of that in a minute.
Somebody has to clean up
Some values are small and fixed: a number, a true or false. Others grow. A piece of text can be one letter or a whole novel, and a list can hold three items or three million. Those values live in memory the program asks for while it runs, and when the program is done with one, that memory should go back.
The hard part is knowing when “done” is. Languages have settled on three answers.
In C, you decide. You ask for memory, and later you hand it back yourself with a call
to free. Forget, and the program slowly fills up. Do it twice, or too soon, and you
get crashes that show up far from the mistake. (The C article shows what that
memory looks like up close.)
In Python, Java, JavaScript, Go and most other languages, a garbage collector decides. That’s a part of the language that runs alongside your program, now and then finds values that nothing can reach anymore, and frees them. It’s safe and comfortable, and it costs some speed and some control over when things happen.
Rust takes a third road. The compiler decides, ahead of time, by following rules
about who owns each value. There’s no garbage collector running, and no free for
you to forget. The cost is that you have to write code the compiler can follow.
Every value has one owner
Here are the rules, as the official Rust book states them:
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.
The owner is usually a variable. Out of scope means the closing brace of the block where that variable was made. Dropped means cleaned up: the memory goes back.
fn main() {
let greeting = String::from("hello");
println!("{greeting}");
}
String::from makes a piece of text the program owns, and greeting owns it. When
main reaches its closing brace, greeting goes out of scope and the text is
dropped. You didn’t write anything to make that happen. That’s the first rule doing
its work.
Now give the text a second name:
fn main() {
let greeting = String::from("hello");
let other = greeting;
println!("{other}");
println!("{greeting}");
}
Run it, and Rust refuses:
error[E0382]: borrow of moved value: `greeting`
--> src/main.rs:5:16
|
2 | let greeting = String::from("hello");
| -------- move occurs because `greeting` has type `String`, which does not implement the `Copy` trait
3 | let other = greeting;
| -------- value moved here
4 | println!("{other}");
5 | println!("{greeting}");
| ^^^^^^^^ value borrowed here after move
In Python or JavaScript, other = greeting gives one piece of text two names. Rust
can’t allow that, because of the third rule: if both names owned the text, both
would drop it at the end of main, and the same memory would be handed back twice.
So let other = greeting doesn’t share the text. It moves it. other is the owner
now, greeting no longer holds anything you’re allowed to use, and the compiler
won’t let you read it.
Read the error again with that in mind. It names the move (“value moved here”) and the later use, and it points at both.
Numbers don’t behave this way:
fn main() {
let a = 5;
let b = a;
println!("{a} {b}");
}
That runs. Small, fixed-size values like numbers are cheap to copy, so Rust copies
them instead of moving them. That’s what the error meant by the Copy trait: a label
for types that get copied on assignment. Text and lists aren’t on that list, because
copying them could mean copying a novel.
If you learned lux first, you’ve never had to think about this, because lux gives
every name its own copy: assign an array to a new name, change the new one, and the
old one stays as it was. That’s what all those .clone() calls in lux convert’s
output are doing. They make a copy everywhere lux would have, so nothing ever moves.
Handing a value to a function
Calling a function is another way to move a value:
fn shout(text: String) -> String {
text + "!"
}
fn main() {
let name = String::from("Ada");
let loud = shout(name);
println!("{loud}");
println!("{name}");
}
The same error, for the same reason. shout takes a String, so the text moves into
shout’s parameter, and shout drops it (or hands it back as part of the result)
when it finishes. main gave it away.
You have three ways out. You can clone it, with shout(name.clone()), which makes
a second copy for shout to own. You can have shout return the original along with
its result, which gets clumsy fast. Or you can let shout look at the text without
owning it. That last one is the everyday answer, and it has a name.
Borrowing: looking without taking
A reference is a value that points at another value without owning it. You make one
with &, and handing someone a reference is called borrowing.
fn shout(text: &str) -> String {
format!("{text}!")
}
fn main() {
let name = String::from("Ada");
let loud = shout(&name);
println!("{loud}");
println!("{name}");
}
&name lends the text to shout for the length of the call. &str is Rust’s type for
borrowed text: a view of some characters that somebody else owns. shout builds a new
String with format! and returns it, and that new text is owned by loud. Nothing
moved out of name, so both lines print.
Sometimes a function needs to change what it borrows. That takes a mutable reference,
written &mut:
fn add_cheer(text: &mut String) {
text.push_str(", hooray!");
}
fn main() {
let mut name = String::from("Ada");
add_cheer(&mut name);
println!("{name}");
}
mut appears twice, and both are deliberate. let mut says the variable may change.
&mut name at the call says this particular call may change it. You can see, reading
main alone, which calls might touch your data and which can only look.
Borrowing has two rules of its own, and between them they cover most of what the compiler will ever tell you:
At any moment, a value can have many shared borrows (
&) or one mutable borrow (&mut), but not both. A borrow can’t outlive the owner it borrowed from.
Many readers, or one writer. And nobody keeps a reference after the thing it points at is gone. The next two sections show why each one is there.
Many readers, or one writer
Here’s a program that looks harmless:
fn main() {
let mut names = vec![String::from("Ada"), String::from("Grace")];
let first = &names[0];
names.push(String::from("Linus"));
println!("{first}");
}
vec! makes a Vec, Rust’s list that grows. first borrows the first name. Then
push adds a name to the list, which needs a mutable borrow of names, and Rust
refuses:
error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let first = &names[0];
| ----- immutable borrow occurs here
4 | names.push(String::from("Linus"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("{first}");
| ----- immutable borrow later used here
Why does it care? A Vec keeps its items side by side in one block of memory. When
the block is full, push asks for a bigger block, moves every item across, and gives
the old block back. If that happened here, first would still point into the old
block, at memory that no longer belongs to the program. That’s called a dangling
reference, and in C or C++ the same program compiles, and usually works, until one day it
prints garbage or crashes.
Rust doesn’t try to predict whether this particular push will need a bigger block.
It applies the rule: while someone is reading, nobody writes. Move the println! above
the push, and the borrow in first is finished before the write starts, so the
program runs.
A borrow can’t outlive its owner
The second rule catches the other way a reference goes bad:
fn main() {
let label;
{
let word = String::from("temporary");
label = &word;
}
println!("{label}");
}
error[E0597]: `word` does not live long enough
--> src/main.rs:5:17
|
4 | let word = String::from("temporary");
| ---- binding `word` declared here
5 | label = &word;
| ^^^^^ borrowed value does not live long enough
6 | }
| - `word` dropped here while still borrowed
7 | println!("{label}");
| ----- borrow later used here
word is dropped at the inner closing brace, and label still points at it. The
error draws the timeline for you: declared here, borrowed here, dropped here, used too
late here.
The stretch of code where a reference is valid is called its lifetime. Rust works
out lifetimes on its own almost everywhere. Now and then it can’t, and asks you to
write one down with a mark like 'a. That’s a topic for later, and you won’t need it
in this article.
Put the pieces together and that’s the bargain. Every value has one owner that drops it. Moving hands it over. Borrowing lends it out, to many readers or one writer, never past the owner’s end. The checker that enforces the borrowing rules is called the borrow checker, and it’s the part of the compiler you’ll argue with most, and learn the most from.
If you came here from C++
You know most of this already, by convention. A Rust
StringorVecowns its memory the way astd::stringorstd::unique_ptrdoes, and drops it at the end of scope: RAII (resource acquisition is initialization), as you’re used to. The differences are in what’s checked. In Rust, moving is the default and copying is the thing you ask for (.clone()), the reverse of C++. Afterstd::move, a C++ object is left in a “valid but unspecified state” and you may keep using it; after a Rust move, using the old name is a compile error. And a C++ reference or iterator can dangle after apush_backor a returned local, where Rust’s borrow checker refuses the program. The C++ article teaches ownership as a discipline you keep; this one is that discipline, enforced.
Values that come in shapes
There’s one more idea Rust leans on everywhere, and you’ll meet it the moment you read
a file or look something up in a list. It also answers a question you may not have
asked yet: if Rust has no null, how does a function say “there’s nothing here”?
A record says a value is this and that: a point is an x and a y. An enum in Rust says a value is this or that: one of a fixed set of cases, and each case can carry its own data. A type like this is often called a sum type.
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Dot,
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(radius) => 3.14159 * radius * radius,
Shape::Rectangle(width, height) => width * height,
Shape::Dot => 0.0,
}
}
fn main() {
let shapes = vec![Shape::Circle(1.0), Shape::Rectangle(2.0, 3.0), Shape::Dot];
for shape in &shapes {
println!("{}", area(shape));
}
}
A circle carries a radius, a rectangle carries two sides, a dot carries nothing. (f64
is a number with a fractional part.) match picks the arm for the case in hand and unpacks its data
into names you can use. Notice the ownership here too: area borrows each shape, and
for shape in &shapes walks the list by reference, so main still owns everything at
the end.
Now delete the Dot arm and run it:
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Dot,
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(radius) => 3.14159 * radius * radius,
Shape::Rectangle(width, height) => width * height,
}
}
fn main() {
println!("{}", area(&Shape::Dot));
}
error[E0004]: non-exhaustive patterns: `&Shape::Dot` not covered
That’s exhaustive matching: a match must cover every case, or the program doesn’t
compile. Its real value shows up later. Add a Triangle case to Shape six months
from now, and the compiler lists every match in your program that needs a new arm.
Two enums in Rust’s standard library do most of the everyday work. The first is
Option, and here is all of it:
enum Option<T> {
None,
Some(T),
}
T is a placeholder for any type, so Option<i64> is “maybe a number” and
Option<&String> is “maybe a borrowed piece of text”. (Writing one definition that
works for every type is called generics; the Swift article is where this
series teaches them.) Rust has no null. A value that might be missing says so in its
type, and since getting at what’s inside means a match, you can’t forget the empty
case:
fn main() {
let names: Vec<String> = Vec::new();
match names.first() {
Some(name) => println!("first: {name}"),
None => println!("the list is empty"),
}
}
first returns an Option<&String>. Look at what’s inside the Some: a borrow.
first doesn’t hand you the name, it lets you look at it, and the list keeps owning
it. Ownership and enums meet all the time like this.
The second is Result, for things that can fail with a reason:
enum Result<T, E> {
Ok(T),
Err(E),
}
fn main() {
for text in ["42", "forty-two"] {
match text.parse::<i64>() {
Ok(number) => println!("{text} is {number}"),
Err(error) => println!("{text}: {error}"),
}
}
}
parse::<i64>() tries to read a number out of text and returns a Result: Ok with
the number, or Err with what went wrong. Errors are ordinary values that you match on.
Many languages use exceptions instead, where a failure jumps out of the function to
whatever code is waiting to catch it; the Java article covers that style.
Go returns a value and an error side by side, and the Go article shows that.
Rust puts both possibilities in one type and makes you open it.
Where Rust says no to a good program
In most languages, a program that is correct gets to run. Rust doesn’t promise that. The borrow checker only accepts what it can prove safe, and some correct programs are beyond what it can prove. You’ll write one sooner or later, look at it, know it’s fine, and get refused anyway.
The usual trouble spot is data that points at itself in a circle. A list where every
item knows the one before and the one after, a family tree where children know their
parents, a game where every character holds a reference to the others: none of these
has one obvious owner, and one owner is the rule. Rust has tools for these cases.
Rc lets several owners share a value and drops it when the last one lets go.
RefCell moves the borrowing rules from compile time to run time, so breaking them
crashes the program instead of stopping the build. They work. They’re also a step away
from the guarantee you came here for.
Beware of reaching for
.clone()andRc<RefCell<…>>just to quiet the borrow checker. Cloning a short string to get unstuck is fine while you’re learning, andlux convertdoes it everywhere because it has to. But when you find yourself wrapping your data inRc<RefCell<…>>so the errors go away, stop. That’s the compiler telling you the design has no clear owner. Pick one. Let one struct own the data, pass borrows down into functions, return new values back up, and when items need to refer to each other, store their positions in aVecinstead of references. The code gets simpler, and the errors go away for a better reason.
A word counter that borrows its words
Time to put ownership to work on a real file. This small command-line tool reads a text file, finds its ten most common words, prints them, and saves the list next to the file. Make a new project:
cargo new wordfreq
cd wordfreq
Replace src/main.rs with this:
use std::env;
use std::fs;
fn main() {
let path = match env::args().nth(1) {
Some(path) => path,
None => {
eprintln!("usage: cargo run -- <file>");
return;
}
};
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(error) => {
eprintln!("can't read {path}: {error}");
return;
}
};
let words = split_words(&text);
let mut counts = tally(words);
sort_by_count(&mut counts);
let report = render(&path, &counts);
print!("{report}");
let out_path = format!("{path}.counts.txt");
match fs::write(&out_path, report) {
Ok(()) => println!("Saved to {out_path}"),
Err(error) => eprintln!("can't write {out_path}: {error}"),
}
}
fn split_words(text: &str) -> Vec<&str> {
let mut words = Vec::new();
for word in text.split(|c: char| !c.is_alphanumeric()) {
if !word.is_empty() {
words.push(word);
}
}
words
}
fn tally(mut words: Vec<&str>) -> Vec<(&str, usize)> {
words.sort();
let mut counts: Vec<(&str, usize)> = Vec::new();
for word in words {
let n = counts.len();
if n > 0 && counts[n - 1].0 == word {
counts[n - 1].1 += 1;
} else {
counts.push((word, 1));
}
}
counts
}
fn sort_by_count(counts: &mut Vec<(&str, usize)>) {
counts.sort_by(|a, b| b.1.cmp(&a.1));
}
fn render(path: &str, counts: &[(&str, usize)]) -> String {
let mut report = format!("The ten most common words in {path}:\n");
for (word, count) in counts.iter().take(10) {
report += &format!("{count:>5} {word}\n");
}
report
}
Then point it at its own source code. Everything after -- goes to your program
instead of to Cargo:
cargo run -- src/main.rs
The ten most common words in src/main.rs:
14 counts
13 path
11 words
10 let
8 1
8 str
8 word
7 Vec
7 mut
6 n
Saved to src/main.rs.counts.txt
Now follow the values, because every one of them has an owner.
main owns path and text. Getting each one meant opening an enum: nth(1) returns
an Option, since you might not have given a file name, and read_to_string returns a
Result, since the file might not be there. Run cargo run with no file, or with a
file that doesn’t exist, and you’ll see the None and Err arms at work.
split_words(&text) borrows the text and returns a Vec<&str>, a list of borrowed
words. No word is copied. Each &str is a view into text, pointing at a few
characters in the middle of it. (The |c: char| ... part is a tiny unnamed function
that tells split where to cut: at anything that isn’t a letter or digit.) Because the
words borrow from text, the borrow checker won’t let text be dropped while they’re
still in use. You didn’t have to say that. With one borrowed input and a borrowed
output, Rust works out that the output borrows from the input.
tally(words) takes the list itself, with no &. The list moves into tally, which
now owns it, so tally is free to sort it in place before counting the runs of equal
words. main can’t use words after this line, and doesn’t need to. What comes back
is a list of pairs, a borrowed word and a count (usize is Rust’s type for counts and
sizes).
sort_by_count(&mut counts) lends the counts out to be changed, and the &mut at the
call tells you so. The little function inside compares two pairs by their counts, the
bigger one first.
render(&path, &counts) only reads, so it borrows both, and it returns a brand new
String that main owns as report.
Finally, fs::write(&out_path, report) takes report with no &. That’s a move.
It’s the last thing that happens to report, so giving it away costs nothing. Try
adding println!("{report}"); after the write and ask the compiler what it thinks.
The full file is in this series’ projects/rust/ folder, with more ideas to try at the
bottom.
What’s left out
Everything left out builds on what you just learned. Writing lifetimes by hand
('a) is the next step for functions whose borrows Rust can’t work out alone. Traits
are Rust’s way of saying what a type can do, and they’re how generics get their power.
Box, Rc and RefCell are the standard tools for ownership shapes beyond “one owner,
many borrowers”. Threads are where ownership pays off most: the same rules that stopped
the dangling reference also stop two threads from writing the same data at once. The
? operator shortens the match on a Result to one character. Iterators and
closures, which the project dipped a toe into, deserve their own chapter. And Cargo has
a test runner built in, cargo test; the Testing piece teaches the
habit with Go’s runner, and it carries straight over.
When you want more, the Rust project’s own material is excellent. The Rust Programming Language, known as the Book, is the standard tutorial, and its fourth chapter covers ownership at greater length. Rust by Example teaches through short runnable programs, and Rustlings gives you small broken exercises to fix while you read.
Ask the compiler why
Every error in this article had a code, and every code has an essay behind it, already on your machine. Run this:
rustc --explain E0382
It explains the use-after-move error from the start of this article, with examples of
how to fix it. Bring it one question: when the compiler’s help: line suggests
.clone(), what does the explanation suggest instead, and which would you pick for
shout?
Related
- C++ teaches ownership and resource lifetime as a convention you keep, and is the step before this one on the ownership path.
- C shows the memory that ownership manages, handed out and handed back by hand.
- Java covers
nulland exceptions, the approachOptionandResultreplace. - Go returns errors as a value and an error side by side.
- Swift teaches generics, the idea behind
Option<T>. - Testing covers the habit of checking your own code, with Go’s built-in runner.
Tested with Rust 1.100 and lux 0.21.2, November 2026.