CodeBlanks Logo Icon CodeBlanks

Return value

Specify the return type with the -> arrow.

Return values

The return type is written with ->. The body's last expression (without a semicolon) is the return value; there's no need to write return:

fn kare(n: i32) -> i32 {
    n * n          // no semicolon → value returned
}

fn mutlak(n: i32) -> i32 {
    if n < 0 { -n } else { n }
}

Accidentally putting ; on the last line turns it into a statement and the function returns (); the compiler reports "mismatched types".

if is an expression

In Rust, if, match and blocks produce values; that's why no ternary operator (?:) is needed:

let yas = 20;
let durum = if yas >= 18 { "yetişkin" } else { "çocuk" };
let kdvli = {
    let fiyat = 100.0;
    fiyat * 1.2
};
println!("{durum} {kdvli}");

The if-else arms must have the same type.

Practice Absolute value

Write the fn mutlak(n: i32) -> i32 function with an if expression and without writing return. Print mutlak(-7) and mutlak(4) on one line.

Starter code

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

Sample solution

main.rs
fn mutlak(n: i32) -> i32 {
    if n < 0 { -n } else { n }
}

fn main() {
    println!("{} {}", mutlak(-7), mutlak(4));
}

Expected output

7 4

Questions and answers

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

1 Why doesn't <code>fn f() -&gt; i32 { 5; }</code> compile?

  • 5 isn't an i32
  • return is missing and required
  • It compiles
  • 5; is a statement; the function returns () but i32 is expected Correct answer

Explanation: The semicolon turns the expression into a statement and discards its value; writing just 5 (or return 5;) compiles.

2 Return type

Question
fn ortalama(a: f64, b: f64) ____ f64 {
    (a + b) / 2.0
}
Answer
fn ortalama(a: f64, b: f64) -> f64 {
    (a + b) / 2.0
}

Explanation: -> declares the function's return type.

3 Body and return

Term Meaning
{ n * n } Returns n * n
{ n * n; } Returns ()
if a { 1 } else { 2 } Expression
return x; Explicit return

All lessons in Beginner