Oxidation 2 - Variables, Shadowing

Variables

In Python, the variables are assigned with the type based on the content.

string_variable = 'some text'
int_variable = 33
print(type(string_variable), type(int_variable))

And, these variables are allowed to change in a program.

In Rust, the variables can either be mutable or immutable. By default, the variables are immutable.

Mutable - Values are allowed to change Immutable - Values are not allowed to change


fn main() {
let default_variable = 2;
println!("The value in default_variable is {}",{default_variable});

default_variable = 3;
//Here, the code will fail.
//Because we tried to modify the immutable variable

println!("The new value in default_variable is {}",{default_variable});

}

This is where Shadowing comes into picture.

When we employ let, the variable’s values can be rebound to the new value.

fn main() {
let default_variable = 2;
println!("The value in default_variable is {}",{default_variable});
let default_variable = 3;
//we used 'let' above line to rebound the variable to new values
println!("The new value in default_variable is {}",{default_variable});

let mut new_variable = 23;
println!("new_variable is {}", {new_variable});
new_variable = new_variable * 2;
//Here, the variable is mutable. And so, the variable can be modified
println!("new_variable is {}",{new_variable})
}

Concluding the variables section.

  • Variables, by default are immutable (can’t unbind its value).
  • Using Shadowing technique we can modify the immutable variables using keyword let immutable_variable = some_other_value
  • Also, we can declare a variable mutable as let mut variable_name

Page source

Page last updated on: 2024-11-06 09:30:05 +0530 +0530
Git commit: a98b4d9


See also