Rust syntax — the parts you need today

Day 1

Rust for bioinformaticians

What this lecture is

  • A guided tour of the Rust syntax used in today’s hands-on exercises
  • Each slide: one concept — what it is, why it works this way, a DNA example

rustup, rustc, cargo

When you install Rust, you get three separate command-line tools:

  • rustup — the installer. Installs Rust, manages versions, updates.
  • rustc — the Rust compiler. Reads .rs source files, writes machine code.
  • cargo — the build tool. Runs the compiler for you, fetches libraries, runs tests.

Day to day you use cargo. The other two run in the background.

What cargo is

Cargo does two jobs:

  1. Build system — turns your source files into an executable
  2. Package manager — fetches and tracks libraries your code depends on

Both jobs in one tool, so the compiler and the dependency list always agree.

What cargo actually does

A horizontal flow diagram. On the left, a light-blue Sources box contains src/main.rs and Cargo.toml with a subtext that Cargo.toml declares edition, deps and name. A green arrow labeled 'cargo build' points right to a light-orange rustc box labeled 'compile + link'. Above the rustc box, a grey External dependencies box lists serde 1.0.193 and clap 4.4.7 with a subtext that they are fetched from crates.io and cached in ~/.cargo/registry; a grey arrow drops down from the deps box into rustc, labeled 'linked in'. From rustc, a green arrow labeled 'produces' points right to a green Output box containing target/debug/my-project, labelled 'an executable, ~MB', plus a note 'no separate Python/JVM needed'. A dashed arrow labeled 'cargo run' drops from the Output box to a small terminal-style box showing '$ cargo run -- ATGC' and 'hello, ATGC!'. A footer reads: 'You type cargo. It invokes rustc, fetches deps, links, and runs the binary — one tool, all the steps.'

One tool drives the whole build.

A cargo project on disk

my-project/
├── Cargo.toml      manifest: project name, version, dependencies
├── Cargo.lock      exact resolved versions (cargo writes this)
├── src/
│   └── main.rs     the entry point — has fn main()
└── target/         build outputs (you never look in here)

The cargo commands you’ll use

cargo new my-project        # scaffold a new project directory
cargo build                 # compile src/ → target/debug/my-project
cargo run                   # compile and execute
cargo run -- ATGC           # compile and execute with arguments
cargo test                  # compile and run all #[test] functions

The -- separates arguments to cargo from arguments to your program.

Variables — let

let length = 1000;
let base = b'A';
let gc = 0.42;

let name = value; binds a name to a value.

The compiler infers the type from the right-hand side.

Why immutable by default?

Two reasons.

1. Local reasoning — when you read code, you want to know what can change.

let length = seq.len();
//   ... many lines of code ...
//   What is `length` here?  Still seq.len(). Always.

2. Threads can’t race on what doesn’t change — only mutable shared data can race.

let mut — opt in to reassignment

let mut gc_count = 0;
for &b in seq {
    if b == b'G' || b == b'C' {
        gc_count += 1;
    }
}
println!("{}", gc_count);

mut is one keyword that says I will reassign this.

How computers store integers

An integer in memory is a fixed-width binary number.

The width is how many bits it occupies. Common widths: 8, 16, 32, 64.

A bit pattern can be read two ways:

  • Unsigned — all bits encode the magnitude. An 8-bit unsigned holds 0..=255.
  • Signed — one bit encodes the sign. An 8-bit signed holds -128..=127.

The same byte, two ways to read it

A single 8-bit byte with all eight bits set to 1. The most-significant bit is highlighted with a 'sign bit?' annotation and dashed arrow. Below the byte, two panels show the two interpretations: as u8 (unsigned) the bits sum to 128+64+32+16+8+4+2+1 = 255; as i8 (signed, two's complement) flipping and adding 1 gives 00000001, so the value is minus one. Footer: same 8 bits in memory, the type picks the reading.

Eight bits set to one, read once as u8 (255) and once as i8 (-1).

Rust’s integer types

The four you’ll see this week:

Type Width Signed Use for
u8 8 bits no one DNA base, one FASTQ quality byte
usize 64 bits no lengths and indices (covered next slide)
i32 32 bits yes values that can be negative — e.g. alignment scores
f64 64 bits — fractions, probabilities, GC content

Rust also has i8, u16, i16, u32, u64, i64, plus u128 / i128. Same naming pattern (u/i + bit width). Full list and ranges on the day 1 — Concepts page.

usize and isize

Two special integer types: as wide as a memory pointer on the target machine.

  • On a 64-bit machine — and every machine you’ll use this week is 64-bit — usize is 64 bits.
  • On a (rare today) 32-bit machine, usize would be 32 bits.

The convention: use usize for lengths and indices.

let n: usize = seq.len();         // .len() returns usize
let first: u8 = seq[0];           // indexing takes usize

Quick recap — where values live in Rust

You saw stack vs heap in the intro. The one-line summary for Rust:

  • Scalars (u8, i32, f64, bool) live directly on the stack.
  • Vec<T> and String are a 24-byte stack header (ptr + len + cap) pointing at the bytes on the heap.
Two regions side by side. On the left, the stack contains a 3-field Vec<u8> struct with rows labelled ptr (8 bytes), len: 5, and cap: 8 - a 24-byte header. On the right, the heap contains an 8-cell allocation; the first five cells hold the DNA bytes b'A', b'C', b'G', b'T', b'A' and the last three cells are dim/empty. A bracket above the first 5 cells reads 'len = 5'; a bracket above all 8 cells reads 'cap = 8'. An arrow runs from the ptr row on the stack to the first cell on the heap. Footer: stack is 24 bytes (3 times 8), heap is 8 bytes; cheap to move because only the 24-byte header is copied and the data never moves with it.

A 24-byte header points at the bytes on the heap.

Recap — why Python is slower

Python boxes every value (wraps it in a heap object with type tag + refcount). Rust stores scalars directly. That’s where most of the speed gap comes from.

A wide diagram titled 'How 42 is stored — Rust vs Python vs R', with three equally-wide vertical columns separated by faint dividers. Column 1, headed 'Rust: let x: i32 = 42;', shows a light-blue Stack region containing a single small cell labelled 'x =' with a large monospace 42 inside, an italic note '(no heap allocation)' below, and beneath the column a bold green annotation '4 bytes total' followed by the footnote 'the value lives directly on the stack; no heap allocation'. Column 2, headed 'Python: x = 42', shows a small light-blue Stack box labelled x with a filled dot and an arrow leaving it that crosses into a light-orange Heap region; the heap region contains a white box labelled PyLongObject with three internal rows reading 'refcount: 1', 'ob_type:' followed by a dot and short arrow trailing off to the italic label 'PyLong_Type', and 'value: 42' with the 42 rendered larger; beneath the column a bold orange annotation '~28 bytes' with the subline '8 (pointer) + 8 (refcount) + 8 (type) + 4 (value) + alignment' and the footnote 'every integer, even 0, gets this treatment'. Column 3, headed 'R: x <- 42L', shows a similar light-blue Stack box labelled x with a dot and arrow leaving it into a light-orange Heap region; the heap box is labelled 'INTSXP (R integer vector)' and contains a lightly-tinted header band reading 'SEXP header (~32 bytes)', then 'length: 1', then 'data[0]: 42' with the 42 rendered larger; beneath the column a bold orange annotation '~40 bytes' with the subline 'every R scalar is a length-1 vector with a full SEXP header' and the footnote 'we'll come back to why this matters less than it looks'. Spanning the full width below all three columns is a light-green callout box reading in bold dark-green 'Same value, three storage layouts. The metadata isn't optional in Python/R — it's how those languages support dynamic typing and garbage collection.', with a smaller grey italic line below: 'Per-value overhead is fine for one scalar. The next slides show what happens when you have a million.'

One scalar, three storage costs.

Overflow

What happens when you add 1 to a u8 that’s already 255?

let mut a_count: u8 = 255;   // counting how many A bases we've seen so far
a_count += 1;
  • Debug build: program panics with a clear message.
  • Release build: silently wraps to 0 (two’s complement arithmetic).

The pragmatic rule: pick a type wide enough that overflow is unreachable.

Picking a type — rules of thumb

Use case Type
One DNA base u8
One FASTQ quality byte u8
Sequence length, vector length, array index usize
Alignment score (can be negative) i32
Read count, contig count u32 or usize
GC content, probability, fraction f64
Yes / no bool

f64 — fractions, but only ~15 digits of precision

f64 stores fractional numbers in 8 bytes — same width as i64, different encoding. Two things to remember:

  • About 15 significant decimal digits of precision (good enough for almost any biological measurement).
  • Results are approximate: 0.1 + 0.2 != 0.3 in f64. Never compare floats with == — compare (a - b).abs() < 1e-9.

Casting with as

Rust never converts numeric types implicitly.

let gc: usize = 42;
let length: usize = 100;

// let frac: f64 = gc / length;            // compile error
// let frac        = gc / length;          //  = 0  (integer division!)

let frac: f64 = gc as f64 / length as f64;       // = 0.42 (GC ratio)

as does the cast. One CPU instruction, usually free.

Other scalar types — f64, bool, char

let gc: f64    = 0.42;        // 64-bit IEEE 754 float (~15 decimal digits)
let ok: bool   = true;        // true or false
let c: char    = 'A';         // ONE UNICODE CODEPOINT — 4 bytes, not 1

For DNA: prefer u8 (one byte) over char (four bytes, Unicode semantics).

bool — one byte, two valid values

Two 8-cell bytes shown stacked. The first byte (false) has all eight bits set to 0 and is labelled 'false to 0x00'. The second byte (true) has seven zeros and a single 1 in the rightmost bit, labelled 'true to 0x01'. A callout panel on the right explains why a whole byte is used for one bit: CPUs read memory byte-aligned, a 1-bit bool would need bit-fiddling on every read; 1 byte is the cheapest read so Rust pays the 8x memory cost for speed; only 0x00 and 0x01 are valid values, anything else is undefined behaviour.

A bool occupies a whole byte: false is 0x00, true is 0x01; a callout explains why a whole byte is used.

Functions

fn gc_content(seq: &[u8]) -> f64 {
    let mut gc: usize = 0;
    for &b in seq {
        if b == b'G' || b == b'C' {
            gc += 1;
        }
    }
    gc as f64 / seq.len() as f64
}

Signature: parameter types after :, return type after ->. Body in { }.

Expressions and statements

A statement does something but produces no value (ends in ;). An expression produces a value.

let x = 5;            // statement (with a let)
let y = {             // a block IS an expression
    let temp = 10;
    temp + 1          //  no `;`  — this value is the block's value
};                    // y == 11

The last expression of a block, without a semicolon, is the block’s value.

if/else

if gc > 0.6 {
    println!("GC-rich");
} else if gc > 0.4 {
    println!("balanced");
} else {
    println!("AT-rich");
}

The condition must be a bool. No “truthy” values — write if x != 0, not if x.

if/else — visualised

Flowchart of the GC-content if/else chain: starting from gc: f64, a diamond tests gc > 0.6; on true it assigns label = "GC-rich", on false it falls through to a second diamond testing gc > 0.4; on true that assigns label = "balanced", on false it assigns label = "AT-rich". All three branches converge to a single end terminator stating that label is now bound. The matching Rust code is shown to the right.

Flow of control through an if / else if / else chain assigning a single value to label.

if is also an expression

let label = if gc > 0.6 {
    "GC-rich"
} else if gc > 0.4 {
    "balanced"
} else {
    "AT-rich"
};

All branches must produce the same type. The whole if produces that value.

for over a range

for i in 0..seq.len() {            // 0, 1, ..., seq.len() - 1
    process(seq[i]);
}

for i in (0..seq.len()).rev() {    // reverse: seq.len() - 1, ..., 0
    // ...
}

for i in 0..=10 { /* 0 through 10, inclusive */ }

for over a slice

A slice (a borrowed view — i.e. read-only access without taking ownership — of a contiguous run of values; here, the bytes of a DNA sequence) is the natural thing to iterate over. We cover borrowing and ownership in depth tomorrow.

for &b in seq {                     // iterate &[u8]; b is u8
    if b == b'G' || b == b'C' {
        // ...
    }
}

The pattern &b destructures the &u8 yielded by iteration down to u8.

for &b in seq — each byte through the body

At the top, a horizontal row of eight cells labelled seq: &[u8] holds the bytes b'A', b'C', b'G', b'T', b'A', b'C', b'G', b'A' with indices 0 through 7 below. Cells at indices 1, 2, 5, 6 (the C and G bases) are tinted light green; the A and T cells are white. From each cell a separate arrow descends into a light-blue function box labelled 'loop body: check & maybe increment gc' containing the two-line snippet 'if b == b'G' || b == b'C' { gc += 1; }'. Arrows from the green cells are green, accompanied by a green '+1' label; arrows from the white cells are grey, accompanied by a grey dash. To the right of the function box sits an accumulator box labelled gc, half filled green, with the final value 'gc = 4' below it, plus a caption 'four +1s from the green cells'. A footer says: 'The pattern &b destructures the &u8 yielded by iteration into a u8 you can compare directly.'

Iteration visits every byte exactly once.

while

let mut start = 0;
while start < qual.len() && qual[start] < threshold {
    start += 1;
}

Use while when the end depends on state, not on a fixed range.

The && short-circuits — qual[start] is only evaluated when start is in bounds.

while — visualised

Flowchart of a while loop: from start = 0, a diamond tests start < qual.len() AND qual[start] < threshold. The true branch (green) goes down to a process box start += 1, then a curved arrow loops back up to the diamond. The false branch (red) exits to the right to an end terminator: start now points at the first kept base. The matching Rust code is shown above the end terminator.

Flow of control through the quality-trim while loop; the body loops back to retest the condition each iteration.

match

match base {
    b'A' => 1,
    b'C' => 2,
    b'G' => 3,
    b'T' => 4,
    _    => 0,
}

Each arm: a pattern, the => arrow, a value (or a block).

match is an expression — the whole thing evaluates to one value.

match — first matching arm wins

Diagram of a match expression with base = b'G'. The input value b'G' enters at the top. Five arms are arranged vertically: b'A' => 1, b'C' => 2, b'G' => 3, b'T' => 4, _ => 0. The first two arms (b'A' and b'C') are faded with a red X over the pattern and labelled no match. The third arm (b'G') is highlighted in green with the input arrow landing on it, an arrow leading to the result 3, and a label match — return this value. The last two arms (b'T' and _) are dimmed and labelled not reached. A vertical arrow on the left says try arms top to bottom; first match wins. A box at the bottom right reads: value of the match expression = 3.

Walking through match base with base = b'G': the first two patterns fail, the third (b’G’) matches and its result becomes the value of the whole expression; the rest are not reached.

Byte literals — b'X'

A literal (a value written directly in source code, like 42 or 'A') prefixed with b is a byte literal — the character’s raw byte value as a u8, fixed at compile time.

b'A' == 65u8                                    // u8 with the ASCII value
b"ACGT" == [b'A', b'C', b'G', b'T']             // an array of u8
b"ACGT".as_slice()                              // a &[u8]

Patterns — alternatives and named catch-all

match base {
    b'A' | b'a' => /* adenine */,
    b'C' | b'c' => /* cytosine */,
    b'G' | b'g' => /* guanine */,
    b'T' | b't' => /* thymine */,
    other       => panic!("unknown base: {}", other as char),
}

| combines alternatives. A name (other) as the last arm captures the unmatched value.

Exhaustiveness — the safety net

enum Strand { Plus, Minus }

match strand {
    Strand::Plus  =>  1,
    Strand::Minus => -1,
    // Add `Strand::Unknown` to the enum later? This match becomes a compile
    // error until we handle the new case.
}

The compiler refuses to compile a match that does not cover every possible value.

DNA is &[u8], not &str

A slice of bytes — &[u8] — is the right type for DNA. Every base is one ASCII byte, indexing is constant time, byte literals drop straight into patterns.

let dna: &[u8] = b"ACGTACGT";          // a byte slice
let len        = dna.len();             // O(1)
let third      = dna[2];                // O(1), returns u8 = b'G'

Why not &str?

&str is UTF-8 (Unicode encoded as variable-width bytes — 1 byte for ASCII, 2-4 for accented letters, CJK, emoji). The type guarantees valid UTF-8 — so slicing into the middle of a character is rejected at runtime, and indexing is O(n) (the compiler has to walk from the start to find character boundaries).

let s: &str = "café";
println!("{}", s.len());       // 5, not 4 — the é is 2 bytes
println!("{}", &s[0..2]);      // "ca"
// println!("{}", &s[0..3]);   // PANICS — byte 3 is mid-character
The string 'café' shown byte-by-byte: c=0x63, a=0x61, f=0x66, é=0xC3 0xA9 (two bytes). Below: the same as bytes in a Vec<u8>, where every byte stands alone. UTF-8 encodes most ASCII bytes as themselves, but accented and non-Latin characters span multiple bytes.

One character is not always one byte.

Printing — println!

println!("hello {}", name);          // {}   default (Display) formatter
println!("{:?}", record);            // {:?} debug formatter
println!("{:.2}%", gc * 100.0);      // float with 2 decimal places
eprintln!("error: {}", msg);         // writes to STDERR

The ! says: this is a macro. The format string is checked at compile time.

panic! — the program reached an impossible state

fn complement(base: u8) -> u8 {
    match base {
        b'A' => b'T',
        b'T' => b'A',
        b'C' => b'G',
        b'G' => b'C',
        other => panic!("unsupported base: {}", other as char),
    }
}

Use panic! for programmer errors — broken preconditions, “can’t happen” cases.

Tests

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn gc_of_acgt() {
        assert_eq!(gc_content(b"ACGT"), 0.5);
    }

    #[test]
    fn gc_of_empty() {
        assert_eq!(gc_content(b""), 0.0);
    }
}
  • Don’t worry about #[cfg(test)] and mod tests — the starter projects already have them; you just add #[test] fn ... inside.
  • Run with cargo test. Today: starter code ships with tests; make them pass.

To the exercises

In a terminal:

cd day1/ex-gc-content
cargo test

Three tests fail. Edit src/main.rs until they all pass. Then exercise 2.