Rust Fundamentals · 15 XP

Expressions and blocks

Rust distinguishes statements (they do something and produce no value) from expressions (they evaluate to a value). Almost everything is an expression, including blocks and if.

A block { ... } evaluates to its last expression, as long as that line has no trailing semicolon:

let area = {
    let side = 4;
    side * side
};   // area is 16

if is an expression too, so it can produce a value. Both branches must have the same type:

let label = if area > 10 { "big" } else { "small" };

Adding a ; after the last line of a block turns it into a statement, and the block then evaluates to () (the empty "unit" value). That is the most common cause of a "mismatched types" error when you try to return a value.

Your task

Write these three public functions. Do not use the return keyword in any of them. (&'static str is the type of text written directly in your code, like "zero"; the course explains the & and 'static parts later.)

  • sign_word(n: i32) -> &'static str returns "negative", "zero" or "positive", using an if / else if / else chain as the last expression.
  • max_of_two(a: i32, b: i32) -> i32 returns the larger number, with if as an expression.
  • shifted_double(x: i32) -> i32 uses a block to add 3 to x, then doubles the result. For example shifted_double(2) is 10.

Next lesson →

Sign in to run your code. It's free.