DEV Community

Danh Võ
Danh Võ

Posted on

[Rust] Place to store values

Like other programing languages, to hold data we need some things called constant and variable.

CONSTANT

We could not change value of a constant. Good choice to store value that is not changed over time.

const SECONDS_OF_ONE_MINUTE: i32 = 60;
const SECONDS_OF_ONE_HOUR: i32 = SECONDS_OF_ONE_MINUTE * 60;
const SECONDS_OF_ONE_DAY: i32 = SECONDS_OF_ONE_HOUR * 24;
Enter fullscreen mode Exit fullscreen mode

VARIABLE

1) Immutable variable (default and favor by Rust):
After assigning a value to a variable by keyword let, we could not re-assign it. For example:

let var = 1;
println!("value: {var}");
var = 2;  // Will cause error at compile time.
println!("value: {var}");
Enter fullscreen mode Exit fullscreen mode

At this point, it is quite similar to constant, right?
But there are 2 things different between immutable variable and constant:

  • We can use variable shadowing to change variable value. Just repeat the let keyword. But there is a small thing behind the scene. Rust creates another new variable with a new memory slot and with a same name. Not the original one. IMO, its functionality seems to run contrary to its name (immutable but changeable by somehow)
let var = 1;
println!("value: {var}");
let var = 2;  // Is OK
println!("value: {var}");
Enter fullscreen mode Exit fullscreen mode
  • Mutable was born to serve this purpose.

2) Mutable variable:
Just put mut keyword after let:

let mut name = "Unknown";
name = "Danh";
Enter fullscreen mode Exit fullscreen mode

Easy huh?

Reference: https://doc.rust-lang.org/stable/book/ch03-01-variables-and-mutability.html

Top comments (0)