Rules for Variable declaration/ Naming convention in Rust

In rust you can name your variable by following below rules:

  • The name of your variable can contain letters, digits, and the underscore character.
  • It must begin with either a letter or an underscore. It should not begin with number.
  • Rust is case-sensitive language so Upper case and Lower case will matter in your variable name.

Immutable and mutable variables

In Rust, variables are immutable by default. That means once a variable is declared, you cannot change its value. This is one of the many attractions in Rust that encourages you to write your code in a way that takes advantage of the safety and concurrency that Rust offers.

Let us understand this with an example.

fn main() {
 let runs = 45_000;
 println!("runs made are {} ",runs);
runs = 60_000;
 println!("runs updated to {}",runs);
}

When you will try to run this program using “cargo run”. Rust compiler will throw below error:

error[E0384]: re-assignment of immutable variable `runs`
 --> main.rs:6:3
 |
 3 | let runs = 45_000;

 | ---- first assignment to `runs`
  Help: make this binding mutable: ‘mut runs’
 6 | runs=60_000;


  | ^^^^^^^^^^^ re-assignment of immutable variable
error: aborting due to previous error(s)


For more information about this error, try ‘rustc - -explain E0384’.

Error: could not compile ‘variables’

The error message indicates that the cause of the error is that you cannot assign twice to immutable variable runs, because you tried to assign a second value to the immutable runs variable.

In your code you may have need to change the value of your variables , so rust provides you ability to do that also. Variables are immutable only by default. You can make them mutable by adding the keyword ‘mut’ in front of the variable name. 

The code to declare a mutable variable is  −

fn main() {
  let mut runs:i32 = 55_000;
 println!("runs scored are {} ",runs);
runs = 95_000;
  println!("runs updated to {}",runs);
}

Now when you will run this code with “cargo run’ you should see the output as:

runs scored are 55000
runs updated to 95000