GitHub

L1 - Beginner

Understanding variables

Understanding variable declaration and initialization


Simple variable declaration & initialization

  • Variables are immutable by default
  • Keyword let is used to declare a variable
  • If the type can be inferred, it can be omitted
fn main() {
let message = "hello world";
println!("{}", message);
}

VS Code Extension

Install the extension rust-analyzer

Initializing Multiple Variables

Order is important here, of course.

fn main() {
let (first, second) = ("hello","world");
println!("{} {}", first, second);
}

Mutable Variables

fn main() {
let mut count = 0;
println!("Before count: {}", count);
count = 3;
println!("After count: {}", count);
}

Constant Variables

  • The value will be resolved during compilation
  • Faster than variables declared using let
  • Name should be in UPPERCASE
  • Type should be provided
fn main() {
const SECRET: &str = "My_PASSWORD@";
println!("Secret: {}", SECRET);
}

Scope

  • Variables are dropped once they are out of scope
  • Mostly similar to javascript ES6 let and const - Block scope
fn main() {
let x = 10;
{
let y= 20;
println!("{} {}", x, y);
}
println!("{} {}", x, y); // Error! - Cannot access `y`
}
  • Variables can be shadowed in nested blocks like javascript
fn main() {
let x = 10;
{
let x= 20;
println!("{}", x); // 20
}
println!("{}", x); // 10
}
  • Variables can be shadowed in same scope (🤕)
fn main() {
let mut x = 10; // unused variable
let x = 20;
println!("{}", x); // 20
}
fn main() {
let mut x = 10; // x is mutable
let x = x; // x is now immutable
println!("{}", x); // 10
}
  • Variables can be shadowed in same scope to a different tyoe(🤕)
fn main() {
let x = 10;
println!("Before: {}", x); // 10
let x = "hello";
println!("After: {}", x); // hello
}

Memory Safety

  • Variables must be initialized before they are used. So Rust don't have something like undefined which is assigned to a variable by default
fn main() {
let x: i32;
println!("{}", x); // Error: use of possibly-uninitialized `x`
}
fn main() {
let x: i32;
if true {
x = 10;
}
println!("{}", x); // Error: use of possibly-uninitialized `x`
}

If Rust can tell a variable is initialized, during the compile time, then there won't be any error

fn main() {
let x: i32;
if true {
x = 10;
} else {
x = 20;
}
println!("{}", x); // 10
}
Previous
Installation