Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
CHAPTER 02 / 21 · THE LANGUAGE

Values, types, and expressions.

Understand bindings, type inference, functions, and the value of a block.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

A value has a type, and a binding gives that value a local name. let introduces a binding; mut permits that binding's value to change. Rust infers many types from use, but the type remains specific once chosen. A number, string slice, and Boolean cannot be exchanged merely because they print similarly. That explicitness is a tool for discovering a mistaken assumption before it becomes runtime behavior.

Rust is expression oriented. A block can produce a value, an if can choose between two values, and a function can return its final expression without a return keyword. A semicolon changes an expression into a statement whose value is discarded. This tiny punctuation difference explains many type errors: a function declared to return i32 may accidentally return the unit type () if its final arithmetic expression has a semicolon.

02 / THE RULES

What Rust is checking.

Scalar types include integers, floating-point numbers, booleans, and chars. Integers have signed or unsigned forms and explicit widths; conversions are deliberate because some values do not fit. Function parameters and return values normally have written types. A function call evaluates its arguments, transfers or borrows values according to their types, and then receives the declared return value.

Formatting macros place values into a string representation. Debug formatting is helpful for inspection, while Display is intended for human-facing text when a type implements it. A formatted message does not alter the source value. Read each example from right to left at an assignment: determine the expression's type first, then ask whether the binding and later operations agree with it.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

Variables, mutability & shadowing

A let binding is immutable unless you opt into mut. Mutation changes the value in an existing binding, so its type stays fixed. Shadowing creates another binding with the same name and can change the type. This is useful when turning raw input into a validated representation. A const is a named compile-time value that needs an explicit type. Prefer the least changeable representation that fits the work: immutable values are easier to reason about, while a small local mutable accumulator is often exactly right.

variables.rs
const MAX_RETRIES: u32 = 3;
fn main() {
    let mut attempts = 1;
    attempts += 1;
    let input = " 42 ";
    let input: u32 = input.trim().parse().expect("valid number");
    println!("attempts={attempts}/{MAX_RETRIES}, input={input}");
}
OUTPUT
attempts=2/3, input=42
  1. MAX_RETRIES has a type and a constant initializer.
  2. mut allows attempts to be updated in place.
  3. The second input shadows a string slice with a parsed u32.

The boundary: Do not add mut just to silence an unrelated error. Decide which value is supposed to change.

EXAMPLE 02

Numbers, booleans & characters

Rust distinguishes signed integers such as i32, unsigned integers such as u64, and platform-sized usize values used for indexing. Floating-point values use f32 or f64 and cannot represent every decimal fraction exactly. A bool is true or false. A char is one Unicode scalar value, which can occupy more than one UTF-8 byte and is not necessarily an entire visible grapheme. Integer overflow behavior depends on build settings; checked arithmetic makes the boundary explicit in every build.

scalar-types.rs
fn main() {
    let temperature: i32 = -4;
    let ready: bool = temperature < 0;
    let symbol: char = '🦀';
    let safe = u8::MAX.checked_add(1);
    println!("{temperature} {ready} {symbol}");
    println!("overflow: {safe:?}");
}
OUTPUT
-4 true 🦀
overflow: None
  1. The signed integer can represent negative temperatures.
  2. checked_add returns None when the result would exceed u8.
  3. Debug formatting prints the Option variant.

The boundary: Casting with as can truncate or reinterpret values. Use TryFrom when a conversion may fail.

EXAMPLE 03

Functions & expressions

Function signatures describe the contract between caller and callee. Parameter types and non-unit return types are written explicitly. Most Rust blocks are expressions: their final expression becomes the value if it has no trailing semicolon. Statements perform actions; a semicolon can turn a value-producing expression into a statement. Keep a function focused enough to test with ordinary values. Prefer returning a result to printing inside low-level logic, so callers can decide how to display it.

functions.rs
fn total(price: u32, quantity: u32) -> u32 {
    price * quantity
}
fn main() {
    let invoice = {
        let shipping = 5;
        total(12, 3) + shipping
    };
    println!("total={invoice}");
}
OUTPUT
total=41
  1. total returns its final multiplication expression.
  2. The inner block computes a value using a local shipping binding.
  3. The example uses small values; production arithmetic still needs bounds or checked operations.

The boundary: A semicolon after the intended final return expression changes the block to return ().

EXAMPLE 04

Formatting & comments

Formatting uses placeholders rather than concatenating everything manually. Display formatting with {} is intended for human-readable values; Debug formatting with {:?} is intended for inspection. Named arguments make output easier to maintain. You can set width, alignment, and precision without changing the underlying value. Comments explain intent, constraints, and surprising decisions. A comment repeating the next line usually adds less value than a clear variable name.

formatting.rs
fn main() {
    let elapsed = 12.3456;
    let samples = [3, 5, 8];
    // Keep report precision stable for readers.
    println!("elapsed={elapsed:.2}ms");
    println!("samples={samples:?}");
    println!("{name:>8} | {count:03}", name = "Rust", count = 7);
}
OUTPUT
elapsed=12.35ms
samples=[3, 5, 8]
    Rust | 007
  1. Precision rounds the formatted float, not the stored variable.
  2. Arrays support Debug output.
  3. Width and zero-padding are presentation choices.

The boundary: Debug output is not a stable interchange format. Use a real format such as JSON for a public protocol.

04 / THE CONNECTION

Keep this model.

Treat an expression as a value with a type. When a line surprises you, check whether it produces a value, discards one with a semicolon, or changes a mutable binding.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.