Part 6 of the series "Rust Programming in Action"

When learning any programming language, variables are the most basic and important knowledge.

If you have learned C, C++, Java, Go or Python, you will find that after defining a variable in these languages, you can usually modify the value of the variable at any time.

For example, in Go:

package main

import "fmt"

func main() {
    age := 18
    age = 20
    fmt.Println(age)
}

The program can run normally.

However, in Rust, if you write code like:

fn main() {
    let age = 18;

    age = 20;

    println!("{}", age);
}

The compiler will report an error directly.

Why?

because All variables in Rust are immutable by default.

This is one of Rust's important designs to ensure memory safety and concurrency safety.

This article will introduce Rust’s variables, immutability, mutable variables, and variable shadowing in detail.


What are variables?

Variable can be understood as:

A name used to save the data.

For example:

fn main() {
    let name = "Rust";
    let age = 10;

    println!("{}", name);
    println!("{}", age);
}

Output:

Rust
10

here:

let name = "Rust";

express:

Define a name called:

name

It saves:

Rust

same:

let age = 10;

save:

10

When you need to use it later:

Just write the variable name directly.


let keyword

Rust uses:

let

Define variables.

grammar:

let variable name = value;

For example:

let name = "Tom";

let age = 18;

let score = 99.5;

Each statement must end with:

;

This is different from Go.


Rust is immutable by default

Let’s look at an example.

fn main() {

    let age = 18;

    age = 20;

    println!("{}", age);

}

Compile:

cargo run

Getting error:

cannot assign twice to immutable variable

means:

Immutable variables cannot be assigned a value again.

The reason is:

let

The ones created by default are:

Immutable variables.

That is to say:

After creation:

Cannot be modified.


Why is Rust immutable by default?

Many beginners will ask:

Why doesn't Rust allow variables to be modified like other languages?

There are three reasons.

1. Avoid accidental modifications

For example:

let price = 100;

After running the program for several thousand lines:

Sudden:

price = 1;

If the project is large.

It's hard to find who modified it.

Immutable by default avoids many of these bugs.


2. Easier to deduce code

For example:

let id = 1001;

Just see:

id

Developers know:

It is always:

1001

Reading code becomes easier.


3. Safer

Immutable objects:

Naturally thread safe.

therefore:

Rust makes it easier to implement high-performance concurrency.


mutable variable

If you really need to modify the variable.

Rust allows:

use:

mut

For example:

fn main() {

    let mut age = 18;

    age = 20;

    println!("{}", age);

}

Output:

20

here:

mut

express:

Mutable.

grammar:

let mut variable = value;

For example:

let mut count = 0;

count += 1;

Totally legal.


Modified multiple times

For example:

fn main() {

    let mut num = 1;

    num = 2;

    num = 3;

    num = 100;

    println!("{}", num);

}

Output:

100

Rust has no limit on the number of modifications.

if only:

The variables are:

mut

That’s it.


Immutable vs mutable

Immutable:

let name = "Rust";

Can:

println!("{}", name);

cannot:

name = "Go";

variable:

let mut name = "Rust";

Can:

name = "Go";

Also possible:

println!("{}", name);

Define multiple variables at once

Rust can define multiple variables in succession.

For example:

fn main() {

    let name = "Alice";

    let age = 20;

    let city = "Beijing";

    println!("{}", name);

    println!("{}", age);

    println!("{}", city);

}

Output:

Alice
20
Beijing

Type automatic deduction

Rust can automatically deduce variable types.

For example:

let age = 18;

The compiler automatically thinks:

i32

Another example:

let pi = 3.14;

Automatic derivation:

f64

therefore:

Many times:

No need to write:

let age: i32 = 18;

direct:

let age = 18;

That’s it.


Explicitly specify the type

certainly.

Also possible:

Specify it yourself.

For example:

let age: i32 = 18;

let score: f64 = 98.5;

let ok: bool = true;

grammar:

let variable: type = value;

Variable Shadowing (Shadowing)

Rust has a very unique feature:

Shadowing.

For example:

fn main() {

    let x = 5;

    let x = x + 1;

    let x = x * 2;

    println!("{}", x);

}

Output:

12

here:

It does not modify the variable.

Instead:

Redefined a new one:

x

The old variable has been shadowed by the new variable.


What is the difference between Shadowing and mut?

Let’s look at two examples.

use:

mut
let mut x = 5;

x = 6;

here:

There is only one:

x

Just modified it.


use:

let x = 5;

let x = 6;

here:

There are actually two variables.

Second one:

Shaded the first one.


Shadowing can change types

This is:

mut

It can't be done.

For example:

let space = "100";

let space = space.len();

println!("{}", space);

Output:

3

first:

space

yes:

&str

Second time:

become:

usize

if:

use:

mut

An error will be reported.

because:

The type cannot be changed.


Common mistakes

Forgot to write mut

For example:

let count = 0;

count += 1;

mistake:

cannot assign twice to immutable variable

solve:

let mut count = 0;

Modification type

For example:

let mut name = "Rust";

name = 100;

mistake:

The types are inconsistent.

Rust is a statically typed language.

Once the type of a variable is determined.

Cannot be modified.


Shadowing is mistaken for modifying variables

For example:

let x = 5;

let x = 6;

Many beginners think:

Modified:

x

Actually:

no.

Instead:

Created:

new variable.


best practices

It is recommended to follow the following principles during development:

  • Immutable variables are used by default.

  • Only use it when you really need to modify it mut.

  • Type conversions prioritize shadowing over forcibly modifying variables.

  • Reduce the scope of mutable variables to reduce the possibility of accidental modification.

  • Give variables meaningful names, e.g. user_name, total_price, avoid using a, b, tmp Unintelligible names.

This not only makes the code safer, but also easier to maintain.


Summary of this chapter

Variables are the most basic concept in Rust programming, andImmutable by defaultThis is one of the biggest differences between Rust and many other languages.

Learned in this article:

  • what is a variable

  • let Define variables

  • Rust is immutable by default

  • mut mutable variable

  • Type automatic deduction

  • explicit type declaration

  • Shadowing

  • mut Differences from Shadowing

  • Common mistakes and best practices

After mastering the design ideas of variables and immutability, you will find that Rust encourages developers to write safer and more predictable code, which is also an important reason why it is favored in large projects and high-concurrency scenarios.


Next article preview

Next article we will learn Rust Data Types,include:

  • integer type

  • floating point type

  • Boolean type

  • Character type

  • Tuple

  • Array

  • type conversion

  • type inference

After learning, you will be able to correctly select and use various basic data types in Rust, laying a solid foundation for subsequent learning about functions, ownership, and structures.