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.