Type inference helps the computer guess the type of a value so you don't have to write it all the time. This makes your code shorter and easier to read.
Type inference in Rust
let variable_name = value;
You can omit the type after let if the compiler can guess it from the value.
If the compiler cannot guess, you must write the type explicitly like let x: i32 = 5;.
x is an integer because 5 is a whole number.let x = 5;name is a string slice &str because of the quotes.let name = "Alice";let pi: f64 = 3.14;numbers is a vector of integers Vec<i32> from the list.let numbers = vec![1, 2, 3];
This program shows how Rust guesses types for age and name but needs the type for height because it is a floating-point number.
fn main() {
let age = 30; // compiler infers i32
let name = "Bob"; // compiler infers &str
let height: f32 = 1.75_f32; // type written explicitly
println!("Name: {}", name);
println!("Age: {}", age);
println!("Height: {} meters", height);
}Type inference works best when the value clearly shows the type.
If the compiler cannot guess, it will give an error asking you to write the type.
Using type inference can make your code cleaner but sometimes adding types helps others understand your code better.
Type inference lets Rust guess variable types from their values.
You can skip writing types when the compiler can figure them out.
Explicit types are needed when the compiler cannot guess or for clarity.
Practice
let x = 5; without specifying a type?Solution
Step 1: Understand Rust's default integer type
Rust usesi32as the default integer type when no type is specified.Step 2: Apply type inference to
Since 5 is an integer literal, Rust inferslet x = 5;xto bei32automatically.Final Answer:
Rust guesses the type ofxasi32based on the value 5. -> Option DQuick Check:
Type inference =i32for integer literals [OK]
- Thinking Rust requires explicit types always
- Assuming default type is string
- Believing missing types cause syntax errors
Solution
Step 1: Identify valid floating-point syntax
In Rust, floating-point literals use a dot (.) as decimal separator, so3.14is valid.Step 2: Check type inference usage
Writinglet num = 3.14;lets Rust inferf64type automatically.Final Answer:
let num = 3.14; -> Option CQuick Check:
Floating-point literals inferf64by default [OK]
- Using comma instead of dot for decimals
- Confusing string literals with numbers
- Unnecessarily specifying type when inference works
let x = 10;
let y = 20.5;
let z = x as f64 + y;
println!("{}", z);Solution
Step 1: Understand type casting
Variablexisi32,yisf64. Castingx as f64converts it to floating-point.Step 2: Calculate the sum
After casting,10.0 + 20.5 = 30.5. Theprintln!prints this value.Final Answer:
30.5 -> Option AQuick Check:
Cast int to float, then add = 30.5 [OK]
- Expecting integer addition without cast
- Assuming implicit cast without
as - Confusing output format with concatenation
let a = 5; let b = 2.0; let c = a + b;
Solution
Step 1: Check variable types
aisi32(integer),bisf64(floating-point).Step 2: Understand addition rules in Rust
Rust does not allow adding different numeric types directly; explicit casting is needed.Final Answer:
Cannot add integer and floating-point without casting. -> Option AQuick Check:
Mixed-type addition requires cast [OK]
- Ignoring type mismatch errors
- Assuming implicit conversion between int and float
- Overlooking Rust's strict type rules
result? let values = vec![1, 2, 3]; let result: Vec<f64> = values.iter().map(|&x| x as f64 * 1.5).collect();
Solution
Step 1: Analyze the iterator and map closure
values.iter()produces references&i32. The closure|&x| x as f64 * 1.5dereferences and castsxtof64, then multiplies.Step 2: Collect into specified type
Thecollect()call collects results intoVec<f64>as explicitly annotated.Final Answer:
Vec<f64> -> Option BQuick Check:
Mapping with cast and collecting matches annotated type [OK]
- Confusing iterator item types with collected vector type
- Missing dereference in closure causing type errors
- Assuming collect infers wrong type without annotation
Ready to prove it?
Pass the test and this pattern moves unknown
