Type Casting
Part of the Fundamentals section of Coddy's Rust journey — lesson 14 of 75.
Type casting is the process of converting a value from one data type to another. In Rust, we use the as keyword for explicit type casting (also known as type conversion).
The most common type conversions are between numeric types:
// Integer to Float conversion
let number: i32 = 5;
let decimal: f64 = number as f64;
// becomes 5.0// Float to Integer conversion
let decimal: f64 = 9.7;
let number: i32 = decimal as i32;
// becomes 9 (decimal part is truncated)Challenge
BeginnerWrite a Rust program that demonstrates type casting. Perform the following operations:
- Declare an
f64variable namedpriceand initialize it with the value99.99. - Cast the
pricevariable to ani32and store the result in a new variable namedint_price. - Print the values of
priceandint_price, to the console.
Cheat sheet
Type casting converts a value from one data type to another using the as keyword:
// Integer to Float conversion
let number: i32 = 5;
let decimal: f64 = number as f64;
// becomes 5.0
// Float to Integer conversion
let decimal: f64 = 9.7;
let number: i32 = decimal as i32;
// becomes 9 (decimal part is truncated)Try it yourself
fn main() {
// Declare and initialize variables
let price: f64 = 99.99;
let int_price: i32 = ?;
// Output the values
println!("Price: {}", price);
println!("Int Price: {}", int_price);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input