CodeBlanks Logo Icon CodeBlanks

Expressions and statements

Learn the difference between expressions and statements.

Expressions and statements

In Rust a statement does something but produces no value (let x = 5;); an expression produces a value (5 + 1, kare(3), if ..., { ... }). Putting a semicolon after an expression turns it into a statement.

let y = {
    let x = 3;
    x + 1        // the block's value: 4
};
println!("{y}");

That's why let x = (let y = 6); is invalid: let doesn't produce a value.

match is an expression too

To classify a value and assign the result directly to a variable, a match expression is used:

let puan = 72;
let harf = match puan {
    90..=100 => 'A',
    70..=89 => 'B',
    50..=69 => 'C',
    _ => 'F',
};
println!("{harf}");   // B

Every arm must return the same type; otherwise the compiler reports an error.

Practice Letter grade

Write the fn harf(puan: u32) -> char function with a match expression: 90–100 'A', 70–89 'B', 50–69 'C', otherwise 'F'. Print harf(95), harf(72) and harf(30) on one line.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn harf(puan: u32) -> char {
    match puan {
        90..=100 => 'A',
        70..=89 => 'B',
        50..=69 => 'C',
        _ => 'F',
    }
}

fn main() {
    println!("{} {} {}", harf(95), harf(72), harf(30));
}

Expected output

A B F

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which of these is an expression?

  • fn f() {}
  • use std::io;
  • { let a = 2; a * a } Correct answer
  • let a = 2;

Explanation: The block produces the value of its last expression (4); the others are declarations and statements that produce no value.

2 if as an expression

Question
let durum = ____ yas >= 18 { "yetişkin" } else { "çocuk" };
Answer
let durum = if yas >= 18 { "yetişkin" } else { "çocuk" };

Explanation: if is an expression; the chosen arm's value is assigned directly to the variable.

3 Code and kind

Term Meaning
let x = 5; Statement
5 + 1 Expression
{ x + 1 } A value-producing block
x + 1; A statement discarding the value

All lessons in Beginner