Rust Type Casting

In Rust, type casting is called "type conversion". Rust provides several ways to convert values from one type to another.

One way to convert between types is to use a type conversion function. Rust provides conversion functions for many of the primitive types, such as as_i32() and as_f64() for integers and floating-point numbers, and as_char() for converting integers to characters. For example:

refer ‮ot‬:theitroad.com
let x: u32 = 42;
let y: i32 = x as i32; // convert u32 to i32
let z: char = y as u8 as char; // convert i32 to u8 to char

In this example, we convert a u32 value to an i32 value using the as keyword and the i32 type name. We also convert the i32 value to a char value using the as keyword and the u8 type name.

Rust also provides a trait called From that allows you to define your own conversion functions for custom types. For example, you can define a from() function for a custom struct to convert it to a string:

struct Person {
    name: String,
    age: u32,
}

impl From<Person> for String {
    fn from(person: Person) -> String {
        format!("{} ({})", person.name, person.age)
    }
}

let alice = Person { name: String::from("Alice"), age: 30 };
let alice_str: String = alice.into(); // convert Person to String

In this example, we define a custom Person struct and a from() function that converts a Person value to a String value. We then use the into() function to convert a Person value to a String value.

It's important to note that not all types can be converted to each other. For example, you cannot convert a string to an integer directly using as. Rust also provides a type conversion method called parse() that allows you to convert strings to numbers.