Skip to content

Borrow Checker

You'll write your first Rust program, get the compiler to refuse three things on purpose, and read what it's telling you instead of fighting it.

About

Rust is the other language this track is written in, and its compiler rejects programs that C would happily build and then crash. The borrow checker enforces one owner per value and no mutable aliasing, which is the memory discipline from the C badges turned into a rule the compiler checks for you. The first week with it feels like arguing with a pedant, so you'll make it refuse three programs on purpose and read the errors slowly, because they're some of the best error messages in any language. Install it with rustup, which is free and takes five minutes.

At a glance

Per requirement
15 XP
Completion bonus
75 XP
Requirements
5
Takes
Two evenings
Skill level
Beginner (done it a few times)
Cost
Free
Supplies
You need some
Where
At home
Other people
On your own

Requirements

  1. 1
    Write a program that reads a file and counts the words, using only the standard library. Use std::fs::read_to_string, split_whitespace and a HashMap. Handle the file not existing with a match or the question mark operator rather than unwrap, so a bad path prints a message instead of a panic. Take a screenshot of the code and a run on a real text file. Photo
  2. 2
    Make the compiler reject a use after move and explain the error in your own words. Create a String, move it into another variable or a function, then try to use the original. Read the full error including the help lines. Write two sentences on what moved and why the compiler cares. Take a screenshot of the error and your note. Photo
  3. 3
    Make it reject two mutable borrows at once, then fix it two different ways. Take two mutable references to the same Vec in the same scope and try to use both. Fix it once by shrinking a scope and once by restructuring the code so only one is needed. Take a screenshot of the error and both fixes compiling. Photo
  4. 4
    Make it reject a reference that outlives its data, then fix it by returning an owned value. Write a function that returns a reference to a local variable. The compiler refuses because the local dies when the function returns, which is the dangling pointer from C caught before you can run it. Take a screenshot of the error and the fix. Photo
  5. 5
    Port your C average program to Rust and compare the two side by side. Same behavior as the First Compile badge, with input parsing that handles a bad line without panicking. Count how many lines each version needs and note which one could crash on bad input. Take a screenshot of both programs and the same input run through each. Photo