Variables in Rust are immutable by default. In this video, explore how they can be made mutable.
- [Instructor] 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 nuggets in Rust that encourages you to write your code in a way that takes advantage of the safety and concurrency that Rust offers. To illustrate, let's generate a new project called variables using cargo. I say "cargo new variables", followed by the bin parameter.
This creates our variable project. Let's go to our Visual Studio Code editor and open this folder. Let's open the main.rs. As you can see here, cargo has generated the code. In Rust we use the keyword "let" to declare and assign values to variables. Let me declare let x equal to five, which means that x is of integer type because five is an integer.
Then let's try to print out the value of x. To print out the value, let's use the print new line macro. Here I pass the string to bring a line and to print out values we use the curly braces as a place holder. Some people prefer this as a template as well. After the double quotes end, just add a comma and the value that you want to print.
I add a semicolon here, to finish my statement. Let's try to change the value of x and again try to print it out. Let's just jump back to our command prompt to run this code. Cd into variables and then hit cargo run. As expected, we get an error saying that Rust cannot assign twice to an immutable variable x.
On the other hand, mutable d can be very useful. Variables are immutable only by default. We can make them mutable by adding the keyword mute in front of the variable name. Let's jump to the code editor to do this. After the let, we just add this keyword mut, which is mutable, and save this file. Let's go back to our power shell to run. Let me just clear screen real quick and do cargo run.
As you can see here, at the first instance the value of x was five and then after we changed it, it became six. In addition to allowing this value to change, it can return to future readers of the code by indicating that other parts of the code will be changing this variable value. Very useful, right.
- Installing Rust
- Data types
- Adjusting memory allocation
- Setting up race conditions
- Working with functions
- Exploring references and borrowing
- Using structs
- Method syntax
- Demonstrating recoverable errors with Result
- Working with enums
- Getting user input