valfz

Rust from the command line

Cargo and a first program

Create the tally project with Cargo, read a log file, count its requests, and learn how a compiler error message is laid out.

lesson
01 of 08
read
9 min

Rust code is built with Cargo, which is both the build tool and the package manager. This lesson uses it to create tally, the access log summarizer this course builds, and gets the program to read a file and count requests. The first version will not compile, on purpose: compiler errors in Rust follow a fixed layout, and knowing how to read one pays off in every later lesson.

Creating the project

Check the toolchain first.

cargo --version
cargo 1.99.1 (5f94df478 2026-08-27)

If the command is missing, install Rust with rustup. Then create a package and enter its directory:

cargo new tally
cd tally
    Creating binary (application) `tally` package
note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

Cargo wrote a manifest and one source file. Unless the directory is already inside a repository, it also initialized Git and added a .gitignore.

tally/
  .gitignore
  Cargo.toml
  src/
    main.rs
Cargo.toml
[package]
name = "tally"
version = "0.1.0"
edition = "2024"

[dependencies]

The edition key selects a revision of the language’s surface rules. Editions exist so that syntax can change without breaking existing code: every crate declares its own, and crates on different editions work together. 2024 is the current one and the one cargo new picks. The [dependencies] table stays empty until lesson 6.

src/main.rs
fn main() {
    println!("Hello, world!");
}

main is where execution starts. println! ends in ! because it is a macro: it is expanded at compile time, which lets the compiler check the format string against the arguments. cargo run compiles the program and runs it; try it now to confirm that the toolchain works. It is one of the commands that cover most of the working day:

Command Effect
cargo check Type-checks the code without producing a binary. The fastest feedback.
cargo build Compiles to target/debug/tally.
cargo run Builds if anything changed, then runs the binary.

Build output lands in target/, which the generated .gitignore excludes. The first build also writes Cargo.lock, a record of the exact version of every dependency. For a program, as opposed to a library, commit it.

A log file to work on

tally reads access logs in the Combined Log Format. It is the format nginx writes unless told otherwise, and the Apache documentation describes each field. Save these 18 lines as access.log in the project directory. The addresses come from ranges reserved for documentation.

access.log
203.0.113.7 - - [28/Nov/2026:09:12:01 +0000] "GET / HTTP/1.1" 200 5123 "-" "Mozilla/5.0"
203.0.113.7 - - [28/Nov/2026:09:12:01 +0000] "GET /static/app.css HTTP/1.1" 200 18230 "https://example.com/" "Mozilla/5.0"
203.0.113.7 - - [28/Nov/2026:09:12:02 +0000] "GET /static/app.js HTTP/1.1" 200 48211 "https://example.com/" "Mozilla/5.0"
203.0.113.7 - - [28/Nov/2026:09:12:02 +0000] "GET /favicon.ico HTTP/1.1" 404 153 "https://example.com/" "Mozilla/5.0"
198.51.100.23 - - [28/Nov/2026:09:13:40 +0000] "GET / HTTP/1.1" 200 5123 "-" "Mozilla/5.0"
198.51.100.23 - - [28/Nov/2026:09:13:41 +0000] "GET /static/app.css HTTP/1.1" 200 18230 "https://example.com/" "Mozilla/5.0"
192.0.2.44 - - [28/Nov/2026:09:14:05 +0000] "POST /api/orders HTTP/1.1" 201 87 "-" "curl/8.7.1"
198.51.100.23 - - [28/Nov/2026:09:14:
203.0.113.7 - - [28/Nov/2026:09:14:30 +0000] "GET /about HTTP/1.1" 200 3310 "https://example.com/" "Mozilla/5.0"
2001:db8::1f - - [28/Nov/2026:09:14:52 +0000] "GET / HTTP/2.0" 200 5123 "-" "Mozilla/5.0"
203.0.113.7 - - [28/Nov/2026:09:15:03 +0000] "GET / HTTP/1.1" 304 - "-" "Mozilla/5.0"
203.0.113.7 - - [28/Nov/2026:09:15:03 +0000] "GET /static/app.css HTTP/1.1" 304 - "https://example.com/" "Mozilla/5.0"
192.0.2.44 - - [28/Nov/2026:09:15:10 +0000] "GET /api/orders HTTP/1.1" 500 312 "-" "curl/8.7.1"
192.0.2.44 - alice [28/Nov/2026:09:15:19 +0000] "GET /admin HTTP/1.1" 403 199 "-" "curl/8.7.1"
192.0.2.201 - - [28/Nov/2026:09:15:22 +0000] "-" 400 0 "-" "-"
198.51.100.23 - - [28/Nov/2026:09:15:48 +0000] "GET /static/app.js HTTP/1.1" 200 48211 "https://example.com/" "Mozilla/5.0"
2001:db8::1f - - [28/Nov/2026:09:16:02 +0000] "GET /favicon.ico HTTP/2.0" 404 153 "https://example.com/" "Mozilla/5.0"
198.51.100.23 - - [28/Nov/2026:09:16:15 +0000] "POST /api/orders HTTP/1.1" 502 166 "https://example.com/" "Mozilla/5.0"

Each line is one request: the client address, two identity fields that are usually -, a timestamp, the quoted request line, the status code, the response size in bytes, and finally the referer and the user agent.

Lines 8 and 15 are damaged on purpose. Line 8 stops in the middle of the timestamp, as happens when a write is interrupted. Line 15 has "-" in place of the request; in these logs a hyphen stands for a value the server did not have. Lesson 4 decides what to do with lines like these.

Reading the file

Replace the generated main.rs with a first attempt at counting requests:

src/main.rs
use std::env;
use std::fs;

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 = 0;
    for line in contents.lines() {
        if !line.is_empty() {
            count += 1;
        }
    }

    println!("{path}: {count} requests");
}

use brings names from the standard library into scope. env::args() is an iterator over the command-line arguments, starting with the program’s own name, so .nth(1) is the first real argument. It returns an Option<String>, because the argument may be missing, and fs::read_to_string returns a Result, because reading can fail. Both types make the caller say what happens in the bad case. expect is the bluntest possible answer: take the value if there is one, otherwise abort with this message. Lesson 4 replaces both calls.

let declares a variable, and the compiler infers its type: path and contents are Strings, count is an integer. Inside a format string, {path} inserts the variable of that name.

Reading a compiler error

The build fails:

cargo build
   Compiling tally v0.1.0 (/home/you/tally)
error[E0384]: cannot assign twice to immutable variable `count`
  --> src/main.rs:11:13
   |
 8 |     let count = 0;
   |         ----- first assignment to `count`
...
11 |             count += 1;
   |             ^^^^^^^^^^ cannot assign twice to immutable variable
   |
help: consider making this binding mutable
   |
 8 |     let mut count = 0;
   |         +++

For more information about this error, try `rustc --explain E0384`.
error: could not compile `tally` (bin "tally") due to 1 previous error

The first and last lines come from Cargo. Everything between them is the compiler’s diagnostic, and every diagnostic has the same parts in the same order. (Later lessons show only the diagnostic.)

It opens with the severity, an error code and a one-sentence summary. The --> line gives the file, line and column of the primary location. Then comes an excerpt of your code with two kinds of underline. ^^^ marks the primary span, the place the compiler objects to. --- marks secondary spans, which explain how things got there; here it points at the first assignment on line 8. Reading the labels from top to bottom usually tells the whole story.

A help: section proposes a concrete edit and shows it as a small diff, with +++ under the text to insert. These suggestions are often exactly right. Some diagnostics also carry a note: section with background. The closing line names a command, rustc --explain E0384, that prints a longer explanation with examples.

As for the error itself: variables are immutable unless declared with let mut. The default is deliberate. A reader can tell from the declaration whether a value changes later, and the borrowing rules of the next lesson rely on the compiler knowing the same thing. Apply the suggested fix on line 8:

src/main.rs
    let mut count = 0;
cargo run -- access.log

Arguments after -- go to your program instead of to Cargo.

   Compiling tally v0.1.0 (/home/you/tally)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
     Running `target/debug/tally access.log`
access.log: 18 requests

Eighteen is the number of lines, the two damaged ones included. Telling a request from garbage takes a parser, which arrives in lesson 3.

What a panic looks like

Give the program a file that does not exist:

cargo run -- nope.log
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/tally nope.log`

thread 'main' (1408826) panicked at src/main.rs:6:46:
could not read file: Os { code: 2, kind: NotFound, message: "No such file or directory" }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

expect found an error where it wanted a value and panicked. The program printed the message together with the source location of the expect call, and exited with status 101. A panic is meant for bugs: situations the programmer believed could not happen. A missing file is an ordinary event, and the person running tally is better served by a plain message than by a position in main.rs. Lesson 4 takes care of that.

The program holds the whole file in one String, and it passes &path to a function without any explanation of the &. The next lesson covers what that symbol means and who owns the text.

Exercises

  1. Print the size of the file next to the count. contents.len() returns the length in bytes. For the sample file the output should be access.log: 18 requests, 1827 bytes.
  2. Remove the loop and the mutable variable, and compute the count with contents.lines().filter(|line| !line.is_empty()).count(). The output should not change, and cargo build should print no warnings.
  3. Change the declaration to let mut count: u8 = 0; and make a 300-line input with yes "$(cat access.log)" | head -n 300 > long.log. Running the program on long.log should end in a panic with the message attempt to add with overflow. Then choose a type that can hold the count.

keyboard

h
home
w c a
writing, courses, about
n p
next and previous lesson
j k
scroll down and up
g G
top and bottom of the page
t
switch light and dark
?
this help

shortcuts are