0
0
Rustprogramming~5 mins

Type inference in Rust

Choose your learning style9 modes available
Introduction

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.

When you want to write simpler code without repeating types.
When the type is obvious from the value you give, like numbers or text.
When you want the compiler to check types but avoid cluttering your code.
When you want the compiler to help find mistakes by guessing types.
When you use variables that get their type from the way you use them later.
Syntax
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;.

Examples
The compiler infers x is an integer because 5 is a whole number.
Rust
let x = 5;
The compiler infers name is a string slice &str because of the quotes.
Rust
let name = "Alice";
Here, the type is written explicitly because the compiler needs to know the exact floating-point type.
Rust
let pi: f64 = 3.14;
The compiler infers numbers is a vector of integers Vec<i32> from the list.
Rust
let numbers = vec![1, 2, 3];
Sample Program

This program shows how Rust guesses types for age and name but needs the type for height because it is a floating-point number.

Rust
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);
}
OutputSuccess
Important Notes

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.

Summary

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.