Variables in Rust

codernineteen·2022년 1월 14일

Rust dev

목록 보기

Variables and immutability

Let and Immuntability

As mentioned already, Variable is immutable by default in Rust.
If you want mutable variable, you can use 'mut' keyword.

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6;
    println!("The value of x is: {}", x);

This code will cause error if there isn't mut keyword.


Constant is also immutable varaible.
But There are a few difference between const and let.

  1. you can't use 'mut' keyword when you use constant.
  2. constant can be declared in any scope.

You can declaration constants with 'const' keyword
const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
As you can see, Rust naming convention for const is to use all uppercase and underscore between words.

Constants are valid for the entire time a program runs. (This is useful when you want to convey this variable with meaning of this name).


There is two variable declaration , but variable name is same, repeating the use of the let keyword. This is shadowing.

fn main() {
    let x = 5;

    let x = x + 1;

        let x = x * 2;
        println!("The value of x in the inner scope is: {}", x);

    println!("The value of x is: {}", x);

If you run, 6 will be output in global, 12 in inner scope.
Difference between shadowing and using 'mut' keyword is that shadowing enables us to peform a few transformations on a value, but after that, it gains immutability again.
Furthermore, by shadowing variable, we can create new variable with same name easily and can change type

fn main() {
    let spaces = "   ";
    let spaces = spaces.len();

If we want to attain same result with mut keyword, it makes compile error.

fn main() {
    let mut spaces = "   ";
    spaces = spaces.len();

//this occur 'mismatched types'

Rust official docs

슈퍼 주니어 개발자

0개의 댓글