CodeBlanks Logo Icon CodeBlanks

Variables with let

Define variables with the let keyword.

Variables with let

let binds a value to a name. In Rust variables are immutable by default; this prevents a value from changing somewhere unexpected. The type is usually inferred from the value, or written explicitly if wanted:

let yas = 36;          // inferred as i32
let boy: f64 = 1.72;   // explicit type
let ad = "Ada";        // &str
println!("{ad} {yas} {boy}");

Type inference

The compiler infers the type from the value and later use. The default for integers is i32 and for decimals f64. When inference isn't enough (e.g. "42".parse()), the type is given explicitly:

let n: i32 = "42".parse().unwrap();
let m = "7".parse::<u8>().unwrap();  // turbofish syntax

Unused variables produce a warning; a name you deliberately don't use starts with _: let _gecici = 1;.

Practice Variables

Use let to declare ad ("Ada"), yas (36) and boy: f64 (1.72) with an explicit type. Print println!("{} {} {}", ad, yas, boy);.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let ad = "Ada";
    let yas = 36;
    let boy: f64 = 1.72;
    println!("{} {} {}", ad, yas, boy);
}

Expected output

Ada 36 1.72

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens with <code>let x = 5; x = 6;</code>?

  • It warns but runs
  • Compile error: assigning twice to an immutable variable Correct answer
  • x becomes 6
  • A run-time panic

Explanation: Rust rejects reassigning an immutable binding at compile time (E0384); changing it requires let mut.

2 Write the type

Question
let fiyat____ = 12.5;
Answer
let fiyat: f64 = 12.5;

Explanation: The type is written after the variable name with a colon.

3 Value and inferred type

Term Meaning
42 i32
3.14 f64
"Ada" &str
true bool

All lessons in Beginner