Rust · Chapter 1 of 26

Rust, and your first program

By the end of this chapter you can say why DoodhSetu writes its collection box in Rust, write a Rust program with fn main, run it with cargo run, build it with cargo build and cargo build --release, print with println! and its placeholders, keep values in variables made with let and let mut, use Rust's basic types (whole numbers, decimals, true or false, and text), convert between them with as, and read the compiler's errors as help. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: The language
  • 4 tasks
  • Rust
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

DoodhSetu, a dairy-tech startup in Anand, Gujarat, runs the software of 120 village milk societies in Anand and Kheda districts. Their 4,800 member farmers pour milk twice a day, from 6 am and from 6 pm. At each society's counter a small collection box weighs every can, reads its fat and SNF (solids-not-fat) from the milk analyser, prints a slip with what the can earned, and at the end of the shift sends the records to the dairy plant. Every ten days Neha, who runs accounts, pays each farmer from those records.

On Monday 12 October an update to the analysers at 23 societies made them send an empty line now and then. The box's program had never met an empty line. At 6:47 am it crashed on the first one, restarted, and crashed again, and the cans poured since its last save were lost. Lakhan, who runs field operations, had his team write 1,940 pourings on paper slips while farmers waited in line with their cans. Neha typed the slips in that night and found 37 with wrong amounts. Ishita, the founder, grew up in a dairy family in Anand: she knows what a stopped counter costs a village at 7 am.

The box needs a program that cannot be surprised by a value it did not plan for, that handles every error the scale and the analyser can send, that starts in a moment after a power cut, and that runs fast in little memory on a small machine. Farhan, DoodhSetu's staff engineer, is rewriting it in Rust, and you write it with him: the box, the payouts, and the plant's service that every box talks to. You do not need to have used Rust before: if you have written a little Python or JavaScript, this lab starts from there.

The lesson

Ten days of payouts

Your lab can show you what Rust gives the box. lab payout works out ten days of payouts, farmer by farmer, from Tuesday's 10,164 pourings, the way Neha's payout run does. It runs the same Rust code twice: once built for debugging, the way cargo run builds while you work, and once built for release, the way the box runs it.

$ lab payout
Ten days of milk: 101640 pourings, 4747 farmers to pay, ₹2,93,19,519.00 in all.
Debug build:   31.5 ms, peak memory 9.1 MB, program file 3095 KB
Release build: 2.6 ms, peak memory 8.8 MB, program file 2695 KB

A release build worked through 1,01,640 pourings in under 3 milliseconds, in less than 9 MB of memory, most of it Tuesday's data itself. The debug build is the same program, compiled quickly and without optimising, so it is about twelve times slower: that is the build you run while you write, and cargo build --release makes the fast one. The program file is the whole program: copy it onto the box and it runs, with nothing else to install and nothing to start first.

Speed is half of it. The other half is the night of 12 October. Rust's compiler refuses to build a program that uses a value which might not be there, or ignores an error that might happen (chapters 8 and 9), so the empty line from the analyser becomes a case the code must handle, found while Farhan writes it and not at 6:47 am at a village counter.

What Rust is

Rust is a programming language first released as version 1.0 in 2015, made for programs that must be both fast and safe: browsers, operating systems, network services, small devices.

  • Compiled: the compiler, rustc, turns your source code into a program file of machine code. Mistakes in names, types and the use of memory are found before the program ever runs.
  • Statically typed: every value has one type, fixed when the program is compiled. Rust usually works the type out for you.
  • Memory safe, with no garbage collector: the compiler knows when each value can be freed, and frees it there (chapter 5 shows how).
  • No null, no exceptions: a value that may be missing, and an operation that may fail, are types you must deal with (chapters 8 and 9).
  • Cargo: one tool that builds, runs, tests and formats your code.

Your first program

cargo new makes a new Rust project, a package:

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

It holds two files. Cargo.toml says what the package is called, which edition of Rust it is written in (2024, the newest), and which other crates (Rust's libraries) it uses: none yet. src/main.rs is the program. With its line changed to DoodhSetu's greeting:

fn main() {
    println!("Namaste from DoodhSetu");
}
$ cargo run
   Compiling hello v0.1.0 (/workspace/chapters/try1/hello)
    Finished `dev` profile [unoptimized] target(s) in 0.10s
     Running `/home/student/.cache/cargo-target/debug/hello`
Namaste from DoodhSetu
  • fn main() is a function called main. Every Rust program starts in main, and ends when main ends. Its code goes between the braces { }.
  • println! prints its text and then a line break. The ! says it is a macro, a piece of code that writes more code for you when the program is compiled; you call it like a function, with the !.
  • Text goes in double quotes, and each statement ends with a semicolon.

cargo run compiles the package, then runs the program. The first three lines are Cargo's own; cargo run -q leaves them out. Cargo keeps what it builds in a target folder. On your own machine that is target/ inside the package; in this lab every chapter shares one, in ~/.cache/cargo-target, so the crates the lab uses are compiled only once.

Forget the ! and the compiler says exactly what to do:

error[E0423]: cannot find function `println` in this scope
 --> nobang.rs:2:5
  |
2 |     println("Namaste from DoodhSetu");
  |     ^^^^^^^ not found in this scope
  |
  = note: a macro named `println` exists in another namespace
help: use `!` to invoke the macro
  |
2 |     println!("Namaste from DoodhSetu");
  |            +

This chapter's programs

In this chapter every task is a whole program with its own fn main, one file each, so the chapter's Cargo.toml names each one as a bin, a program the package builds:

[[bin]]
name = "welcome"
path = "welcome.rs"

With four of them, Cargo needs to know which to run:

$ cargo run
error: `cargo run` could not determine which binary to run. Use the `--bin` option to specify a binary, or the `default-run` manifest key.
available binaries: payout, report, society, welcome

So you run one by its name: cargo run --bin welcome. Cargo compiles only that file, so a mistake in another task's file does not stop it.

cargo build, and --release

cargo build compiles without running; cargo build --release compiles with every optimisation the compiler has:

$ time cargo build --release
   Compiling hello v0.1.0 (/workspace/chapters/try1/hello)
    Finished `release` profile [optimized] target(s) in 0.30s
real	0m0.325s
$ ls -l ~/.cache/cargo-target/release/hello
-rwxr-xr-x 2 student student 468872 Oct 25 01:40 /home/student/.cache/cargo-target/release/hello
$ time ~/.cache/cargo-target/release/hello
Namaste from DoodhSetu
real	0m0.005s

One file of 458 KB holds the whole program, and it starts and finishes in 5 milliseconds. After a power cut, the box is counting cans again almost before the inverter has settled.

Printing with println!

println!("{} has {} members", "Boriavi", 34);
let village = "Boriavi";
let members = 34;
println!("{village} has {members} members");
print!("Morning shift");
print!(" is open\n");
println!("{:.1} litres, fat {:.1}%", 4.88, 4.2);
println!("{} | {} | {}", "B2002", 34.0, true);
println!("{:?} | {:?}", "B2002", 34.0);
Boriavi has 34 members
Boriavi has 34 members
Morning shift is open
4.9 litres, fat 4.2%
B2002 | 34 | true
"B2002" | 34.0
  • Each {} in the text is a placeholder, filled by the next value after the text, in order.
  • {village} names a variable inside the braces, and prints its value there: shorter, and harder to get in the wrong order.
  • print! adds no line break; \n inside the quotes is one.
  • {:.1} prints a decimal with one digit after the point, rounded (4.88 became 4.9); {:.2} gives two. It works with a name too: {litres:.2}.
  • {:?} is the debug form, made for programmers: text keeps its quotes, and 34.0 keeps its .0, which {} leaves out.

Variables: let and let mut

A variable is a name for a value, made with let:

let village = "Boriavi";
let members = 34;
let open = true;
let mut cans = 0;
println!("{village}: {members} members, open {open}, {cans} cans");

cans += 1;
cans = cans + 1;
println!("{cans} cans");
Boriavi: 34 members, open true, 0 cans
2 cans
  • A variable made with let alone never changes. Rust calls it immutable.
  • let mut makes one that may change. = gives it a new value, and cans += 1 is short for cans = cans + 1.
  • Every variable has a value from the start: there is no undefined.

Try to change a variable without mut, and the program does not build:

error[E0384]: cannot assign twice to immutable variable `cans`
 --> change.rs:3:5
  |
2 |     let cans = 0;
  |         ---- first assignment to `cans`
3 |     cans += 1;
  |     ^^^^^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     let mut cans = 0;
  |         +++

Why make you say it? In a long program, a value that cannot change is one less thing to keep in your head: members is 34 on every line below. Only the variables marked mut can surprise you, and they are easy to find.

The basic types

typeholdsexamples
i32whole numbers, up to about 2.1 billion either way34, -3, 2980
i64whole numbers, up to about 9.2 billion billion2931951900
f64decimal numbers4.88, 0.1
booltrue or falsetrue
texttext in double quotes (its type is written &str)"B2002"

A whole number with no type said is an i32, and a decimal an f64. Arithmetic on whole numbers stays whole: / drops the remainder, and % gives the remainder:

let minutes = 157;
println!("{} h {} min", minutes / 60, minutes % 60);
println!("{} {}", 7 / 2, 7.0 / 2.0);
2 h 37 min
3 3.5

Decimal numbers are close, not exact:

let a = 0.1;
let b = 0.2;
println!("{}", a + b);
0.30000000000000004

That is fine for litres on a slip and wrong for money. So DoodhSetu keeps every amount as whole paise in an integer: ₹29.80 a litre is 2980, and a farmer is never paid a fraction of a paisa wrong. Milk is whole millilitres (4.88 litres is 4880), and fat and SNF are tenths of a percent (4.2% is 42).

Rust never mixes types

A whole number and a decimal are different types, and Rust will not multiply one by the other:

error[E0277]: cannot multiply `{float}` by `{integer}`
 --> mismatch.rs:4:25
  |
4 |     let amount = litres * rate;
  |                         ^ no implementation for `{float} * {integer}`
...

({float} and {integer} mean "some decimal" and "some whole number": the compiler had not yet picked which exact type.) To mix them, convert one with as. With let litres = 4.88; and let rate = 2980;:

println!("{}", litres * rate as f64);
println!("{}", (litres * rate as f64) as i32);
14542.4
14542

rate as f64 is the whole number as a decimal. as i32 turns a decimal into a whole number by dropping its decimals, without rounding. Converting can lose something, so Rust does it only where your code says so, and you can see every place it happens.

The compiler is on your side

Rust's errors are long because they teach. Each starts with error, often a code such as E0384, then the file, line and column (change.rs:3:5), the line itself with the place marked, and often a help: with the fix. rustc --explain E0384 prints a page about any error code.

A warning is different: the program still builds and runs. A variable you never use gives one:

warning: unused variable: `members`
 --> unused.rs:3:9
  |
3 |     let members = 34;
  |         ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_members`

The compiler also checks in rounds. First it reads the code and fills in macros like println!, then it checks every type, and only when the types are right does it check how values are used and changed. A program with mistakes of every kind shows the first round's errors; fix them, run again, and the next round's appear. Fix the first error first, run again, and repeat: each round leaves the program closer to one that is right before it ever runs at a village counter.

Your turn

Four tasks, one file each, at the top; run each with cargo run --bin and its name. Task 1 prints the collection box's two welcome lines. Task 2 prints the Napad society's card from variables, with the cans count made with let mut. Task 3 works out what one can of buffalo milk earned from three variables: the Check also runs it with other numbers, so compute everything from them. Task 4 is an interview question: Lakhan's shift report will not compile, in more than one round, and once it does it can still print the wrong percent. Farhan will ask why Rust makes you write mut, and why it will not divide a whole number by a decimal until you say so.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    welcome.rs: the collection box says hello

    When a society's collection box starts, it prints two lines. Make welcome.rs print exactly these two lines, in this order:

    DoodhSetu collection box is starting

    Society S001 Karamsad, morning shift, 186 members

    Letters, spaces and numbers must match exactly, with nothing else printed. The Check builds and runs welcome.rs on its own, as cargo run --bin welcome does.

  2. Task 2

    society.rs: one society's card

    Lakhan wants a card for the society at Napad. Keep each fact in its own variable made with let (the Check looks for at least five): the id S014, the village Napad, the district Anand, founded 1973, members 56, the box B2014, and open true. The cans count is different, because it changes: make it with let mut, starting at 0, and add 1 to it for each of the three cans that arrive.

    Then print exactly these six lines, from the variables:

    Society S014 at Napad, Anand

    Founded in 1973

    Members: 56

    Collection box: B2014

    Open: true

    Cans so far: 3

    A variable made with let alone can never change, so adding to it is a compile error until it is let mut.

  3. Task 3

    payout.rs: what one can of milk earns

    A can of buffalo milk held 5250 millilitres, with 6.4% fat and 9.1% SNF, kept in the variables ml, fat and snf (fat and SNF in tenths of a percent: 64 and 91). Keep the three lines let ml = 5250;, let fat = 64; and let snf = 91; exactly as they are, work out from them, and print exactly:

    Milk: 5.25 litres

    Rate: 4016 paise a litre

    Amount: 21084 paise

    Amount: 210 rupees 84 paise

    Litres are ml divided by 1000, with their decimals. The buffalo rate chart pays 40 paise for each tenth of fat and 16 paise for each tenth of SNF, for a litre. The amount in paise is ml times the rate, divided by 1000, a whole number. The rupees are the whole hundreds of the amount and the paise what is left over.

    The Check also runs payout.rs with ml 3125, fat 58 and snf 88 in those three lines, and then it must print Milk: 3.125 litres, Rate: 3728 paise a litre, Amount: 11650 paise and Amount: 116 rupees 50 paise.

  4. Task 4 · interview question

    Interview: report.rs, the report that will not build

    After the morning shift at Karamsad, Lakhan wrote report.rs for the shift's report, and it does not compile. Fix it so that it prints exactly:

    Pourings: 211

    Rejected: 6

    Accepted: 205

    Accepted: 97.16 percent

    Accepted means poured and not rejected. The percent is accepted divided by pourings, times 100, with its decimals, printed with two digits after the point (the last println! line does that). Keep the lines let pourings = 211; and let rejected = 6; exactly as they are: the Check also runs report.rs with 180 and 9 in them, and then the last two lines must be Accepted: 171 and Accepted: 95.00 percent.

    Farhan will ask: why are Rust's variables unchangeable unless you write mut, and why will Rust not divide a whole number by a decimal until you convert one with as?

What you will learn

  • Why Rust: fast, small programs whose mistakes the compiler finds before they run.
  • fn main and println!: the shape of every Rust program, and printing.
  • Cargo: cargo new, Cargo.toml, cargo run, cargo build and --release.
  • Placeholders: {}, {name} and {:.2} in the text you print.
  • Variables: let, and let mut for the ones that change.
  • The basic types: i32, i64, f64, bool and text, and as to convert.
  • The compiler's errors: what they say, and why they come in rounds.

More in The language

Build "Rust, and your first program" yourself

DoodhSetu runs the milk collection boxes of 120 village societies around Anand. The old box program crashed on an empty line, and you rebuild it in Rust. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.