Rust for beginners — Part 3 — Variables

Manikandan SP
3 min readFeb 24, 2022

--

Let’s look into how we can use variables in rust

Note: Kindly have a look into the previous section of tutorial to understand about rust compiler, cargo and writing your first piece of code in rust

Previous section: https://medium.com/@manikandan96372/rust-for-beginners-part-2-rust-compiler-cargo-and-write-your-first-piece-of-rust-code-e2602e722e46

All the following code in this section is written in “main.rs” file which was created in the previous section.

fn main() {
let a = 1;
println!("{}", a);
let name = "Tom";
println!("{}", name);
}

On executing the above snippet, you will get the following output

1
Tom

Variables in rust are declared using the keyword “let” followed by the variable name and a value assigned to that variable.

Note: In the above code snippet the print statement is used as println!(“{}”, a), where “{}” is used as a placeholder for the following value to be displayed which is “a” here.

Let’s try re-assigning a value to the variable,

fn main() {
let a = 1;
a = 2;
println!("{}", a);
}

On executing the above snippet, you will get the following error on your terminal

Cannot assign twice ? Shouldn’t we have access to re-assign values to the variables ? It’s a common scenario right ? So how do we achieve re-assigning values to a variable ?

It is achieved through “mut

By nature, variables in rust are immutable, so if we have to re-assign values to them or make them mutable, we should declare those values as “mut” variables as following,

fn main() {
let mut a = 1;
a = 2;
println!("{}", a);
}

In this case, when you execute it, it should give the following output

2

Since variable “a” is declared as “mut” mutable variable, re-assigning is possible in this case.

Now let’s see how variables are handled as constants in rust

fn main() {
const a: i32 = 1;
a = 2;
println!("{}", a);
}

Constants in rust are declared using the keyword “const”, but when you try to re-assign values to const variables, you will receive the following output

You cannot re-assign values to const variables in rust, they are immutable in nature, but wait ? can’t we make it mutable by adding the “mut” keyword ?

No, we can’t. irrespective of marking it as mut or not, const variables are immutable in nature.

Also, there is one special thing about variables in rust, it is called “shadowing”,

fn main() {
let a = 1;
let a = 2;
println!("{}", a);
}

On executing the above snippet, you will receive the following output,

2

But how ? It is possible to declare the same variable twice with “let” keyword and it will take the latest value that is assigned to it when it is dispalyed,this is called as “shadowing

Let’s continue in the next section to discuss about data types in rust

--

--