Start learning free

LESSON 16 OF 348 · VARIABLES

Type Conversion in Rust in Rust

Lesson

In Rust, every value has a type: i32, f64, String, and so on. Sometimes you need to convert a value from one type to another.

Common type conversion functions:

x.to_string()              // converts i32 or f64 → String
s.parse::<i32>().unwrap()  // converts &str → i32
s.parse::<f64>().unwrap()  // converts &str → f64
x as i32                   // casts f64 → i32 (drops decimal)

Here are some examples:

let score: i32 = 42;
let score_str = score.to_string();   // "42"

let weight: f64 = 70.8;
let weight_int = weight as i32;      // 70  (decimal dropped)

let count = "100";
let count_int: i32 = count.parse().unwrap();  // 100

Note that casting an f64 to i32 with as i32 simply drops the decimal - it does not round.


Assignment
Follow the Coding Tutorial and convert each variable to a different type!


Hint
Use .to_string(), as i32 casting, and .parse().unwrap().

STEP 1 OF 3
    Ctrl + Enter to check

    Type Conversion in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free