» Quick Introduction to Rust » 1. Basics » 1.6 Type Mechanisms

Type Mechanisms

Casting

In Rust, explicit type casting can be performed using the as keyword.

fn main() {
    let decimal = 65.79_f32;
    // Explicit conversion
    let integer = decimal as u8;
    let character = integer as char;

    println!("{} {} {}", decimal, integer, character);
    // 65.79 65 A
}

Inference

The type Inference mechanism not just looks at the type of the value expression during an initialization, but also looks at how the variables is used afterwards.

fn main() {
    let a = 5u8;

    let mut vec = Vec::new();
    // At this point the compiler doesn't know the element type of `vec`

    vec.push(a);
    // Now the compiler knows that `vec` is a `Vec<u8>`

    println!("{:?}", vec); // [5]
}

Aliasing

The type keyword can be used to give a new name to an existing type.

type NanoSecond = u64;
type Duration = i64;

fn main() {
    let duration: NanoSecond = 58 as u64;
    println!("{} nanoseconds", duration); // 58 nanoseconds
}

Code Challenge

Try to modify the code provided in the editor to implement the conversion functions.

Loading...
> code result goes here
Prev
Next