Learn / Rust / Types and functions: a unit converter

Rust, lesson 3 of 5

Types and functions: a unit converter

Every value in Rust has a type. The common ones:

  • i32: whole numbers, such as 42 or -7
  • f64: numbers with a decimal point, such as 9.5
  • bool: true or false
  • &str and String: text

A function lists the type of each input, and -> shows the type it gives back. The last line, written without a semicolon, is the answer:

fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    println!("{}", add(2, 3));
}

Here is a converter, as engineers use every day. {:.2} shows 2 decimal places:

fn mm_to_inches(mm: f64) -> f64 {
    mm / 25.4
}

fn main() {
    println!("{:.2}", mm_to_inches(100.0));
}

Rust will not quietly mix types. Adding a whole number to a decimal is refused until you convert one of them, which stops a whole class of rounding bugs:

fn main() {
    let a: i32 = 5;
    let b: f64 = 2.5;
    println!("{}", a + b);
}

Rust refuses to build this.

Check yourself

1. Which type holds a whole number such as 42?

2. In fn add(a: i32, b: i32) -> i32, what does -> i32 mean?

3. Why is a + b refused when a is an i32 and b is an f64?

4. How does a Rust function give back its answer?