In part 1 we installed Rust, set up an editor and wrote a small word counter. A lot of that program was written on trust. You saw let mut, &str, usize, a match, a for loop, and a function whose last line had no return, and I asked you to take them on faith.
This part pays that back. We go through the everyday syntax properly: how variables work and why they are immutable by default, what shadowing is, why Rust has twelve integer types where JavaScript has one number, why there are two string types, how functions return values, why if is an expression, and the three kinds of loop. At the end we come back to wordfreq and use all of it to add a --top N option, input validation and a few statistics.
As before, everything here was run, not written from memory. The outputs and compiler errors are copied from Rust 1.100.0 in the official Docker image. I've also put the matching TypeScript next to the Rust in most places, because the fastest way to learn a second language is to notice where it disagrees with your first.
If you skipped part 1, you need a working Rust install and an editor with rust-analyzer. Part 1 covers that on Windows, macOS and Linux.
Setting up a playground
Make a project to experiment in:
cargo new basics
cd basics
You can paste each example into src/main.rs and run cargo run. I find it nicer to keep them all, so here's a trick. Any file in src/bin/ becomes its own program. Create src/bin/vars.rs, src/bin/numbers.rs and so on, and run each with:
cargo run --bin vars
That's how I ran every example in this article, and it means you end up with a folder of small working references you can come back to.
If you want to try something quickly without a project at all, play.rust-lang.org, the official Rust Playground, runs Rust in the browser. Examples in this series that work on their own have a Run link next to Copy, which opens them in the Playground, ready to run and change. That includes the examples that fail to compile on purpose, so you can read the error yourself and try the fix. Short snippets without a main function get wrapped in one on the way, which is all the Playground needs.
Variables
Immutable by default
fn main() {
let price = 100;
let mut quantity = 2;
quantity += 1;
println!("{quantity} items at {price}");
}
3 items at 100
let creates a variable. Without mut, it can't be changed after it's set. With mut, it can. In TypeScript terms, Rust's let is your const, and Rust's let mut is your let.
| TypeScript | Rust |
|---|---|
const price = 100; |
let price = 100; |
let quantity = 2; |
let mut quantity = 2; |
You already saw the compiler error for changing an immutable variable in part 1. The reason Rust defaults this way is that most variables never need to change, and when you read code, knowing that a value is fixed removes a whole category of questions. When something does change, the mut stands out. It also matters a lot for the ownership rules in part 3, where the compiler needs to know who is allowed to modify what.
Notice also that price has no type written down. Rust infers it, here as i32, the default integer type. Your editor's inlay hints will show : i32 in grey after the name. Rust is statically typed, so every variable has exactly one type that is known at compile time, but you only have to write it when the compiler can't work it out.
Shadowing
This is the feature that looks like a mistake to people coming from JavaScript:
fn main() {
let input = "42";
let input: i32 = input.parse().unwrap();
let input = input * 2;
println!("input is now {input}");
}
input is now 84
Writing let input again doesn't change the old variable. It creates a new variable with the same name, which hides, or shadows, the previous one from that point on. The first input is a string, the second is a number parsed from it, the third is that number doubled.
In TypeScript you'd get Cannot redeclare block-scoped variable. In Rust it's normal, and it's mostly used for exactly this case: transforming a value through a few steps without inventing names like inputStr, inputNum and inputDoubled.
The .parse() call converts a string to a number, and since it could fail (what if the string is "hello"?), it returns a Result. .unwrap() means "give me the value, or crash if it failed". It's fine in throwaway examples. In real code you handle the error, which we do in the wordfreq section later.
Shadowing is different from mut in two ways. First, the type can change, which mut can't do:
fn main() {
let mut input = "42";
input = input.len();
println!("{input}");
}
error[E0308]: mismatched types
--> src/bin/e_mut_type.rs:3:13
|
2 | let mut input = "42";
| ---- expected due to this value
3 | input = input.len();
| ^^^^^^^^^^^ expected `&str`, found `usize`
A mut variable can change its value but never its type. input was decided to be a &str (a string slice, more on that soon) on line 2, so line 3 can't put a number in it.
Second, shadowing respects blocks. A shadow inside { } disappears when the block ends:
let input = 84;
{
let input = "inner";
println!("inside the block: {input}");
}
println!("after the block: {input}");
inside the block: inner
after the block: 84
Constants
const MAX_RETRIES: u32 = 3;
const is for values that are known at compile time and never change, like configuration limits. The type is always required, and the convention is SCREAMING_SNAKE_CASE. Constants can be declared outside any function, at the top of a file, which let can't. There's also static for global values that live at a fixed memory address, but you'll rarely need it, and mutable statics require unsafe, so ignore them for now.
Naming
Rust uses snake_case for variables and functions, PascalCase for types, and SCREAMING_SNAKE_CASE for constants. The compiler warns you if you write let userName, which feels pushy until you notice that every Rust codebase reads the same way. Clippy and rustfmt enforce the rest.
Number types
This is the first place Rust and JavaScript really part ways.
JavaScript has one number type, a 64-bit float, plus BigInt for when that isn't enough. Rust makes you choose, because the choice affects memory use, speed and correctness.
Integers
| Size | Signed | Unsigned |
|---|---|---|
| 8 bits | i8 |
u8 |
| 16 bits | i16 |
u16 |
| 32 bits | i32 |
u32 |
| 64 bits | i64 |
u64 |
| 128 bits | i128 |
u128 |
| pointer size | isize |
usize |
i means signed (can be negative), u means unsigned (zero and up). The number is the size in bits. Here's what that means for range:
u8 range: 0 to 255
i32 range: -2147483648 to 2147483647
u64 max: 18446744073709551615
You can print those yourself with u8::MIN, u8::MAX and so on.
Which should you use? In practice:
i32when you don't have a reason to pick something else. It's the default for integer literals.usizefor anything that counts or indexes into a collection: lengths, positions, counts.vec.len()returns ausize, and indexing requires one. It's 64 bits on a 64-bit machine.u64ori64for IDs, timestamps and money stored as cents, where you need more range thani32gives you.u8for raw bytes.
The rest exist for specific cases like file formats, network protocols and memory-tight data structures.
Why this matters coming from JavaScript
Here's a number JavaScript can't hold exactly:
fn main() {
let big = 9_007_199_254_740_993_i64; // 2^53 + 1
println!("i64 keeps it exact: {big}");
println!("as f64 it becomes: {}", big as f64);
}
i64 keeps it exact: 9007199254740993
as f64 it becomes: 9007199254740992
A 64-bit float, which is what every JavaScript number is, can only represent integers exactly up to 2^53. Past that it rounds. This is why database IDs from Twitter's old API arrived as strings in JSON, and why you sometimes see IDs off by one in JavaScript frontends. In Rust an i64 is exact all the way to its limit.
Two details in that snippet. Underscores in number literals are ignored, so 9_007_199_254_740_993 is easier to read than 9007199254740993. And a suffix like _i64 sets the type of a literal directly. You'll also see 0xff for hex, 0b1010 for binary, and 0o777 for octal.
Integer division
7 / 2 = 3
7.0 / 2.0 = 3.5
-7 / 2 = -3, -7 % 2 = -1
Dividing two integers gives an integer, rounded toward zero. In JavaScript 7 / 2 is 3.5. This one bites people who port calculations: averages and percentages done with integers silently lose the fraction. Convert to a float first when you want a fraction.
Floats
Rust has f64 (the default, same as a JavaScript number) and f32 (half the size, less precision). They behave exactly like JavaScript numbers, including the famous rounding:
0.1 + 0.2 = 0.30000000000000004
Never store money in floats, in any language. Use integer cents in an i64, or a decimal crate like rust_decimal when you need fractions of cents.
No silent mixing
JavaScript converts between number kinds quietly. Rust never does:
fn main() {
let price = 20;
let total = price * 1.5;
println!("{total}");
}
error[E0277]: cannot multiply `{integer}` by `{float}`
--> src/bin/e_mix.rs:3:23
|
3 | let total = price * 1.5;
| ^ no implementation for `{integer} * {float}`
(The full error goes on to list every type that can be multiplied, which I've cut. When an error message lists fifty alternatives, the first three lines are the part to read.)
You convert explicitly with as:
let total = price as f64 * 1.5;
This feels tedious for about a week. Then you start to notice that every conversion in your code is visible, and that the bugs you used to get from "5" * 2 and 0.1 * 3 style mistakes don't happen.
as is a blunt tool
as never fails. It converts however it can, which sometimes means quietly losing data:
300 as u8 = 44
-1 as u32 = 4294967295
3.99 as i32 = 3
300 doesn't fit in a u8, so as keeps the low 8 bits, giving 44. -1 as unsigned becomes the largest u32. A float to int conversion truncates toward zero. These are all well defined, not undefined behaviour like in C, but they're rarely what you want. Use as for conversions you know are safe, such as i32 to f64 or u8 to u32. For conversions that might not fit, use try_from, which returns an error instead of guessing. We'll use it when we get to error handling in part 5.
Overflow
What happens if a calculation goes past the type's limit? This program adds 10 to a u8:
fn main() {
let args: Vec<String> = std::env::args().collect();
let start: u8 = args.get(1).map(|s| s.parse().unwrap()).unwrap_or(250);
let next = start + 10;
println!("{start} + 10 = {next}");
}
The odd-looking first two lines read the starting number from the command line, falling back to 250, so the compiler can't work out the answer in advance. Here's what happens in a normal debug build:
thread 'main' (439) panicked at src/bin/overflow.rs:4:16:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
And with a starting value that fits:
5 + 10 = 15
And the same 250 in a release build, with cargo run --release:
250 + 10 = 4
That's important enough to repeat. In debug builds, integer overflow is a crash, called a panic in Rust. In release builds, by default, it wraps around silently, so 250 + 10 in a u8 becomes 4. The reasoning is that overflow checks cost a little speed, debug builds catch mistakes during development, and release builds prioritise performance. You can turn checks on in release with overflow-checks = true in your Cargo.toml profile, which I'd do for anything handling money or quantities.
When overflow is a real possibility, say so in code and choose what should happen:
let level: u8 = 250;
println!("checked_add: {:?}", level.checked_add(10));
println!("saturating_add: {}", level.saturating_add(10));
println!("wrapping_add: {}", level.wrapping_add(10));
checked_add: None
saturating_add: 255
wrapping_add: 4
checked_add returns None if it overflowed, or Some(result) if it didn't. That's the Option type from part 1's table, and you'll see it everywhere. saturating_add stops at the maximum. wrapping_add wraps on purpose. {:?} in the format string means "debug formatting", which can print things like None that don't have a user-facing format.
The compiler also catches overflow it can see in advance:
let volume: u8 = 256;
error: literal out of range for `u8`
--> src/bin/e_range.rs:2:22
|
2 | let volume: u8 = 256;
| ^^^
|
= note: the literal `256` does not fit into the type `u8` whose range is `0..=255`
Booleans and characters
bool is true or false, one byte. There's no truthiness. An if needs an actual bool:
let count = 3;
if count {
println!("we have some");
}
error[E0308]: mismatched types
--> src/bin/e_truthy.rs:3:8
|
3 | if count {
| ^^^^^ expected `bool`, found integer
Write if count > 0. No 0 is false, no empty string is false, no null exists to be false. You'll see this in code review comments in every language: "be explicit about what you're checking". Rust just makes it a rule.
char is a single Unicode character, written in single quotes. It is four bytes, not one, so it can hold any Unicode scalar value:
let ch = 'é';
let crab = '🦀';
é 🦀 sizes: char=4 bool=1
Single quotes are always a char and double quotes are always a string. 'hello' is a compile error.
Tuples and arrays
A tuple groups a fixed number of values that can have different types:
let point: (i32, f64, &str) = (3, 4.5, "label");
let (x, y, name) = point;
println!("tuple: {x} {y} {name} first={}", point.0);
tuple: 3 4.5 label first=3
You can destructure it, like array destructuring in JavaScript, or access fields by position with .0, .1 and so on. Tuples are handy for returning more than one value from a function, which we'll do shortly.
An array in Rust is a fixed-size list of values of one type, and the size is part of the type:
let days = ["mon", "tue", "wed"];
println!("array of {}: {:?}", days.len(), days);
array of 3: ["mon", "tue", "wed"]
The type of days is [&str; 3], three string slices. It can never grow. What JavaScript calls an array, a list that grows and shrinks, is Vec<T> in Rust, the type we used for command line arguments in part 1. Part 8 covers vectors, hash maps and the rest of the collections properly. For now, if you need a list whose length changes, it's a Vec.
Indexing past the end of an array or vector is a panic in Rust, never a silent undefined. If you want "maybe there's an element there", use .get(index), which returns an Option.
Strings
Every Rust beginner asks why there are two string types. The short answer is that one owns its text and one borrows it.
String and &str
fn main() {
let literal: &str = "café";
let mut owned: String = String::from("café");
owned.push_str(" au lait");
owned.push('!');
println!("{literal} has {} bytes and {} chars", literal.len(), literal.chars().count());
println!("owned: {owned}");
}
café has 5 bytes and 4 chars
owned: café au lait!
String is an owned, growable string. It lives on the heap, you can append to it, and when the variable that owns it goes away, the memory is freed. It's the closest thing to a JavaScript string you can build up.
&str, pronounced "string slice", is a borrowed view into some string data that lives somewhere else. String literals like "café" are &str, pointing at text baked into your program's binary. A &str can also point into part of a String. You can read through a &str, but you can't grow it.
The mental model I'd use for now: String is like having the file, &str is like having a link to the file. Part 3 explains this properly, because it's the ownership system in miniature.
The practical rules for today are simple:
- Function parameters that only read text should take
&str. It accepts both string literals and&Stringvalues, so it's the most flexible. - Return
Stringwhen a function builds new text. - Store
Stringin structs that need to own their text.
fn greet(name: &str) -> String {
format!("hello, {name}")
}
fn main() {
let literal = "café";
let owned = String::from("café au lait!");
println!("{}", greet(literal));
println!("{}", greet(&owned));
}
hello, café
hello, café au lait!
greet takes a &str, so we can pass a literal directly or borrow a String with &owned. format! works like println! but returns a String instead of printing. It's the Rust version of a template literal.
Building and changing strings
let first = String::from("Rust");
let second = String::from("acean");
let joined = first + &second;
joined: Rustacean
+ works, with a twist that will make sense after part 3: the left side must be an owned String, and it gets consumed. After that line you can't use first any more. For anything more than joining two strings, format!("{first}{second}") is clearer and doesn't consume anything.
The methods you'd expect are there, under mostly familiar names:
<div> upper=<DIV> trimmed=[hi]
contains? true starts? true
replace: a/b/c
0: one
1: two
2: three
That's to_uppercase(), trim(), contains(), starts_with(), replace() and split(), the last one combined with enumerate() to get an index. The JavaScript versions are toUpperCase(), trim(), includes(), startsWith(), replaceAll() and split().
Bytes, not characters
"café".len() returned 5, not 4. Rust strings are always UTF-8, and len() counts bytes. The é takes two bytes in UTF-8. To count characters, use .chars().count().
JavaScript's length counts UTF-16 code units, which is also not characters: "🦀".length is 2 in JavaScript. Every language has to make a choice here, and Rust's is to be honest that strings are bytes and give you explicit tools for characters.
This is why you can't index a string by position:
let word = String::from("hello");
let first = word[0];
error[E0277]: the type `str` cannot be indexed by `{integer}`
--> src/bin/e_index.rs:3:22
|
3 | let first = word[0];
| ^ string indices are ranges of `usize`
|
= help: the trait `SliceIndex<str>` is not implemented for `{integer}`
= note: you can use `.chars().nth()` or `.bytes().nth()`
The error tells you the two options: .chars().nth(0) for the first character, or .bytes().nth(0) for the first byte. Both return an Option, because the string might be shorter than you asked for. For the first character specifically, .chars().next() is the usual way:
first char: Some('c')
You can slice a string by byte range, &literal[0..3], which gave caf. But if the range lands in the middle of a character, the program panics:
let word = "café";
println!("{}", &word[0..4]);
thread 'main' (500) panicked at src/bin/slicepanic.rs:3:25:
end byte index 4 is not a char boundary; it is inside 'é' (bytes 3..5 of string)
That's a crash on purpose. The alternative would be producing invalid text, and Rust refuses to do that. In web code this matters for things like truncating user names or post previews: use .chars().take(n).collect::<String>() to cut by characters, never byte slicing on text from users.
Functions
Parameters and return types
fn add(a: i32, b: i32) -> i32 {
a + b
}
Parameters always have types. Rust infers types inside functions, but never across function boundaries, so a function signature is always a complete description of what goes in and what comes out. That's also what makes rust-analyzer's hover information so useful.
The return type comes after ->. And there's no return keyword, because the function body is a block, and a block's value is its last expression.
Expressions and statements
This is the single most important syntax idea in Rust, so it's worth slowing down for.
An expression produces a value: a + b, 5, add(2, 3), an if, a match, a block { }. A statement does something and produces no value: let x = 5;, or any expression with a semicolon after it.
The semicolon is what turns an expression into a statement. Watch what happens if you add one to the last line of add:
fn add(a: i32, b: i32) -> i32 {
a + b;
}
error[E0308]: mismatched types
--> src/bin/e_semicolon.rs:1:27
|
1 | fn add(a: i32, b: i32) -> i32 {
| --- ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
2 | a + b;
| - help: remove this semicolon to return this value
You will hit this error. Everyone does. With the semicolon, the function's body ends with a statement, so it produces nothing, which Rust writes as (), the empty tuple, called the unit type. The function promised an i32 and returned (). The help line tells you exactly which semicolon to remove.
return still exists, for leaving a function early:
fn describe(n: i32) -> &'static str {
if n < 0 {
return "negative";
}
if n == 0 { "zero" } else { "positive" }
}
-5 is negative, 0 is zero, 8 is positive
The convention is return for early exits and a plain last expression for the normal result. The &'static str return type means "a string slice that lives for the whole program", which is what string literals are. The 'static part is a lifetime, a topic for part 3. For now, read it as "returns a string literal".
Blocks being expressions also means any { } can compute a value:
let total = {
let base = 10;
let tax = 2;
base + tax
};
block value: 12
base and tax exist only inside the block. This is a neat way to keep temporary variables from leaking into the rest of a function.
Functions that return nothing
fn log(message: &str) {
println!("[log] {message}");
}
No -> means the function returns (). You can actually capture it:
[log] side effects only
log returned ()
This is the same as a TypeScript function returning void, except () is a real value you can store and print. It sounds like trivia, but it's why things like Result<(), Error>, meaning "either succeeded with nothing to report, or failed with this error", work cleanly. You'll write that type a lot in the web part of the series.
Returning several values
Return a tuple and destructure it:
fn min_max(values: [i32; 4]) -> (i32, i32) {
let mut min = values[0];
let mut max = values[0];
for v in values {
if v < min {
min = v;
}
if v > max {
max = v;
}
}
(min, max)
}
let (lo, hi) = min_max([4, -2, 9, 1]);
min -2, max 9
What Rust functions don't have
No default parameter values, no optional parameters, no overloading by argument type, and no named arguments. Coming from TypeScript this feels limiting. The Rust ways around it are separate functions with clear names (new and with_capacity), an Option parameter, or a config struct, which is effectively named arguments. We'll see all three as the series goes on.
Control flow
if is an expression
Because if is an expression, it can produce a value, which is why Rust doesn't need a ternary operator:
let stock = 3;
let label = if stock > 0 { "in stock" } else { "sold out" };
in stock
TypeScript: const label = stock > 0 ? "in stock" : "sold out";
Both branches must produce the same type, because label can only have one type:
let label = if in_stock { "available" } else { 0 };
error[E0308]: `if` and `else` have incompatible types
--> src/bin/e_arms.rs:3:52
|
3 | let label = if in_stock { "available" } else { 0 };
| ----------- ^ expected `&str`, found integer
| |
| expected because of this
No parentheses around the condition, and braces are always required, even for one line. rustfmt and the compiler will both nag you if you write if (x > 0).
match, a first look
match is Rust's switch, and much more. Parts 4 and 5 cover it properly, but it's too useful to leave out of a control flow section:
let status = 404;
let text = match status {
200 => "ok",
301 | 302 => "redirect",
400..=499 => "client error",
_ => "something else",
};
404: client error
Each line is a pattern, then =>, then the value for that case. | means "or". 400..=499 is an inclusive range. _ matches anything. There's no fall-through and no break.
The compiler checks that a match covers every possible value. Remove the _ line and it refuses to compile, because status could be, say, 500, and no arm handles that. In TypeScript you'd get undefined at runtime. This exhaustiveness check is one of the features Rust developers miss most when they go back to other languages, and it gets much more powerful with enums in part 4.
loop
loop runs forever until you break. And break can carry a value out:
let mut attempts = 0;
let result = loop {
attempts += 1;
if attempts == 3 {
break attempts * 10;
}
};
loop gave 30 after 3 attempts
It's the natural fit for retry logic: keep trying until something succeeds, then break with the result.
while
let mut countdown = 3;
while countdown > 0 {
print!("{countdown} ");
countdown -= 1;
}
println!("liftoff");
3 2 1 liftoff
Same as JavaScript, minus the parentheses. print! is println! without the newline. Rust has no ++ or -- operators, on purpose. Use += 1 and -= 1.
for
for in Rust always iterates over something. There's no C-style for (let i = 0; i < n; i++). Instead, you iterate over a range:
for i in 0..3 {
print!("{i} ");
}
for i in 1..=3 {
print!("{i} ");
}
for i in (0..10).rev().step_by(3) {
print!("{i} ");
}
0 1 2 (0..3)
1 2 3 (1..=3)
9 6 3 0 (rev, step 3)
0..3 is 0, 1, 2, excluding the end. 1..=3 includes it. Ranges are iterators, so you can chain methods like .rev() and .step_by().
To loop over a collection with its index, use .iter().enumerate():
let langs = ["ts", "go", "rust"];
for (index, lang) in langs.iter().enumerate() {
println!("{index} -> {lang}");
}
0 -> ts
1 -> go
2 -> rust
That's langs.forEach((lang, index) => ...), or for (const [index, lang] of langs.entries()). Notice the order is (index, value), the opposite of forEach.
Breaking out of nested loops
Loops can have labels, written with a leading apostrophe, so break and continue can target an outer loop:
'outer: for row in 0..3 {
for col in 0..3 {
if row * col == 2 {
println!("found 2 at ({row}, {col})");
break 'outer;
}
}
}
found 2 at (1, 2)
JavaScript has the same feature with outer: labels, though few people use it there.
TypeScript and Rust, side by side
Here is a cheat sheet of everything in this part. Keep it open while you do the exercises.
| TypeScript | Rust |
|---|---|
const x = 5; |
let x = 5; |
let x = 5; x = 6; |
let mut x = 5; x = 6; |
const MAX = 3; (module level) |
const MAX: u32 = 3; |
number |
i32, i64, u8, usize, f64 and friends |
bigint |
i128, u128, or a big-number crate |
Number("42") |
"42".parse::<i32>() (returns a Result) |
Math.floor(x) for int conversion |
x as i32 (truncates) |
7 / 2 is 3.5 |
7 / 2 is 3, 7.0 / 2.0 is 3.5 |
boolean, truthy values |
bool only, no truthiness |
string |
String (owned) and &str (borrowed) |
`hello ${name}` |
format!("hello {name}") |
s.length (UTF-16 units) |
s.len() (bytes), s.chars().count() (chars) |
s[0] |
s.chars().next() |
[1, 2, 3] that can grow |
vec![1, 2, 3] (Vec<i32>) |
[x, y] as a pair |
(x, y) tuple |
function add(a: number, b: number): number { return a + b; } |
fn add(a: i32, b: i32) -> i32 { a + b } |
void |
() |
cond ? a : b |
if cond { a } else { b } |
switch |
match (exhaustive, no fall-through) |
for (let i = 0; i < n; i++) |
for i in 0..n |
arr.forEach((x, i) => ...) |
for (i, x) in arr.iter().enumerate() |
while (true) { ... } |
loop { ... } |
i++ |
i += 1 |
Back to wordfreq
Time to use this. We'll add three things to the word counter from part 1:
- A
--top Noption to choose how many words to show, with proper validation. - Line count, the longest word, and the average words per line.
- A small bar chart made of
#characters, plus rank numbers.
Here's the new main and a new helper function. count_words and the tests from part 1 stay as they were.
use colored::Colorize;
use std::collections::HashMap;
use std::env;
use std::fs;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
eprintln!("usage: wordfreq <file> [--top N]");
process::exit(1);
}
let path = &args[1];
let mut top = 5;
if args.len() >= 4 && args[2] == "--top" {
top = match args[3].parse::<usize>() {
Ok(n) if n > 0 => n,
_ => {
eprintln!("--top needs a whole number above 0, got {:?}", args[3]);
process::exit(1);
}
};
}
let text = match fs::read_to_string(path) {
Ok(contents) => contents,
Err(error) => {
eprintln!("could not read {path}: {error}");
process::exit(1);
}
};
let counts = count_words(&text);
if counts.is_empty() {
println!("{path} has no words in it");
return;
}
let total_words = text.split_whitespace().count();
let line_count = text.lines().count();
let longest = longest_word(&counts);
let average = total_words as f64 / line_count as f64;
println!(
"{line_count} lines, {total_words} words, {} unique",
counts.len()
);
println!(
"longest word: {longest} ({} chars)",
longest.chars().count()
);
println!("{average:.1} words per line");
println!();
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);
println!("{:>2}. {:<10} {count:>3} {bar}", rank + 1, word.bold());
}
}
fn longest_word(counts: &HashMap<String, usize>) -> &str {
let mut longest = "";
for word in counts.keys() {
let longer = word.chars().count() > longest.chars().count();
let tie_but_earlier =
word.chars().count() == longest.chars().count() && word.as_str() < longest;
if longer || tie_but_earlier {
longest = word;
}
}
longest
}
And one more test inside the existing tests module:
#[test]
fn longest_word_prefers_alphabetical_on_ties() {
let counts = count_words("bb aa ccc ddd");
assert_eq!(longest_word(&counts), "ccc");
}
Run it against the same notes.txt:
cargo run -q -- notes.txt
3 lines, 27 words, 16 unique
longest word: compiler (8 chars)
9.0 words per line
1. is 4 ####
2. the 4 ####
3. cargo 3 ###
4. and 2 ##
5. compiler 2 ##
With --top 3, only the first three rows print. And bad input is handled without a crash:
cargo run -q -- notes.txt --top three
--top needs a whole number above 0, got "three"
cargo run -q -- notes.txt --top 0
--top needs a whole number above 0, got "0"
Both exit with status 1. The three tests pass:
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
What's new in that code
let mut top = 5; is a mutable variable with a default, which we overwrite only if the option was given. The if checks there are enough arguments before indexing args[3], because indexing past the end of a Vec would panic.
args[3].parse::<usize>() uses the turbofish, ::<usize>, to tell parse which type to produce. It's the same as writing let n: usize = args[3].parse()..., just inline. Parsing to usize also rejects negative numbers for free, because usize can't be negative.
Ok(n) if n > 0 => n is a match arm with a guard. It only matches if parsing succeeded and the number is above zero. Everything else, a parse error or a zero, falls to _. One match handles three cases without any nesting.
total_words as f64 / line_count as f64 converts both counts to floats before dividing, because integer division would have given us 9 with no decimal. {average:.1} prints one decimal place.
text.lines() splits on line breaks, and handles both \n and Windows \r\n endings, so the same program counts lines correctly on every OS.
longest_word takes &HashMap<String, usize>, a borrowed map, and returns &str. The returned slice points at one of the keys inside the map, so it borrows from the map. Rust works out that the returned &str can only be used while the map is still alive. That's a lifetime being inferred for you, and part 3 explains it. The function compares by .chars().count() rather than .len(), so a word with accented letters isn't counted as longer than it is.
"#".repeat(**count) builds the bar. The double ** is because count here is a reference to a reference to the number: sorted holds references into the map, and .iter() hands out references to those. Each * follows one reference. You'll rarely need two, and part 3 makes this feel less strange.
{:<10} left-aligns in 10 columns, and {:>2} right-aligns in 2, which is how the table lines up.
Exercises
Try these before moving on. Each one uses only what's in this part.
- Add a
--min Noption towordfreqthat hides words with fewer than N occurrences. Validate it the same way as--top. - Print the shortest word as well as the longest. Write a test for it first, then the function.
- Write a function
fn truncate(text: &str, max_chars: usize) -> Stringthat cuts text to at mostmax_charscharacters and adds...if it cut anything. Test it with"café au lait"and a limit of 4, which should givecafé.... Don't use byte slicing. - Write
fn grade(score: u32) -> charthat usesmatchwith ranges to turn 90 to 100 into'A', 80 to 89 into'B'and so on. What does the compiler say if you forget the case for scores over 100? - Make
wordfreqprint the percentage each top word represents, with one decimal place. Watch out for integer division.
Next up: ownership
You've now seen most of Rust's everyday syntax, and you've written a program that handles bad input without exceptions. You've also hit a few things I waved away: why first + &second consumes first, what the & really means, why &str can borrow from a String but String can't come from nowhere, and what that 'static was about.
All of that is ownership, which is part 3, out tomorrow. It's the idea that makes Rust different from every language you've used, and the reason the compiler catches memory bugs before your code runs. We'll take it slowly, with diagrams and JavaScript comparisons, and by the end the borrow checker should feel like a strict but fair code reviewer instead of an obstacle.
If you're wondering where all this leads, the Rust web frameworks comparison shows what we're building toward in the second half of the series.