Type Inference
Part of the Fundamentals section of Coddy's Rust journey — lesson 12 of 75.
In Rust, type inference allows the compiler to automatically deduce the type of a variable based on its value and usage. This means you often don't need to explicitly specify the type when declaring a variable, making your code more concise and easier to read.
For example:
let x = 5;
// Rust infers that x is an i32
let y = 3.14;
// Rust infers that y is an f64
let message = "Hello, world!";
// Rust infers that message is a &str (string)
let is_true = true;
// Rust infers that is_true is a boolIn these examples, we didn't specify the types of x, y, message, and is_true. The Rust compiler automatically inferred their types based on the values assigned to them.
Type inference is not only convenient but also helps to prevent errors. The compiler checks how the variables are used and ensures that the inferred types are consistent throughout the code. If there's a conflict, the compiler will generate an error.
Challenge
BeginnerWrite a Rust program that demonstrates type inference. Declare and initialize the following variables without explicit type annotations:
- A variable named
quantitywith the value10. - A variable named
pricewith the value99.99. - A variable named
messagewith the value"Coddy is awesome!". - A variable named
is_availablewith the valuetrue.
After declaring these variables, use println!() to output their values to the console. Observe how Rust infers the types of these variables based on their values.
Cheat sheet
Rust's type inference allows the compiler to automatically deduce variable types based on their values, eliminating the need for explicit type annotations in many cases.
let x = 5; // Rust infers i32
let y = 3.14; // Rust infers f64
let message = "Hello, world!"; // Rust infers &str
let is_true = true; // Rust infers boolThe compiler checks variable usage to ensure type consistency and will generate errors if there are conflicts.
Try it yourself
fn main() {
// Declare variables here
// Output the values
println!("Quantity: {}", quantity);
println!("Price: {}", price);
println!("Message: {}", message);
println!("Is available: {}", is_available);
}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