Variables and Data Types in Rust
Variables in rust are by default immutable. Immutability describes the state of been unable to change. This means that once a value is bound to a variable, that variable cannot be bound to another value. The code below will fail with a compile error because the program tries to change the value of x from 5 to 6.
fn main() {
let x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
Rust does this to ensure to data integrity which is often a problem in concurrency and ensure that no parts of a code accidentally modifies the value of variable. However, it also provides support to allow you mutate a variable if you need to do so. You can declare a variable as mutable using the code below
fn main() {
let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");
}
The mut keyword informs rust that the variable is mutable. Rust also support constants. The main difference between constants variables and immutable variables, is that you define constant variables using the const keywork. Example;
fn main() {
const PI = 3.14;
}
As per convention, constants variables are written in all capital letters.
Variable Shadowing In Rust
Rust allows you to declare a new variable using the same name as the previous variable. This is very useful, when you want to change the data type of a variable without having to create a new variable with a different name.
let spaces = "testcode";
let spaces = spaces.len();
In the code above, spaces is variable to contains a string testcode. In the next line, spaces is redeclared to be a type of an integer, which is the length of the string.
Recommended by LinkedIn
Data Types In Rust
Rust being a statically typed programming language it needs to know the data type of every variable as compile time. Just like in every programming language, rust supports different types of data types, some examples include
The differences between tuples and array are
Unlike in other programming languages, rust ensures memory safety with arrays when accessing elements of the arrays by checking that the index is not equal to or more than the length of the array. If the index is more than the length of the arrays, the rust program panics and terminates the program rather than allowing you access unsafe memory location. This exception only happens at runtime because there is no way for the rust complier to know at compile time the index the program wants to access.
For more reading checkout Chapter 3 of the Rust book