Index
- Guessing Game
- Common Programming Concepts
- Understanding Ownership
- Using Structs
- Enums and Pattern Matching
- Managing Growing Projects with Packages, Crates, and Modules
- Defining Modules to Control Scope and Privacy
- Paths for Referring to an Item in the Module Tree
- Bringing Paths into Scope with the use Keyword
- Separating Modules into Different Files
- Common Collections
- Error Handling
- Generic Types, Traits, and Lifetimes
- Writing Automated Tests
- Object Oriented Programming
- Adding dependancies
- Option Take
- RefCell
- mem
- Data Structure
- Recipe
- Semi colon
- Calling rust from python
- Default
- Crytocurrency With rust
- Function chaining
- Question Mark Operator
- Tests with println
- lib and bin
- Append vector to hash map
- Random Number
- uuid4
- uwrap and option
- Blockchain with Rust
- Near Protocol
- Actix-web
Variables and Mutability
By default variables are immutable.Use mut to make it mutable.
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
Differences Between Variables and Constants
First, you aren’t allowed to use
mut
with constants. Constants aren’t just immutable by default—they’re always immutable.Here’s an example of a constant declaration where the constant’s name is
MAX_POINTS
and its value is set to 100,000const MAX_POINTS: u32 = 100_000;
Shadowing
fn main() {
let x = 5;
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
}
let x = 5;
let x = x + 1;
let x = x * 2;
println!("The value of x is: {}", x);
}
See that mut is not used.
This program first binds
x
to a value of 5
. Then it shadows x
by repeating let x =
, taking the original value and adding 1
so the value of x
is then 6
By using
let
, we can perform a few transformations on a value but have the variable be immutable after those transformations have been completed.The other difference between
mut
and shadowing is that because we’re effectively creating a new variable when we use the let
keyword again, we can change the type of the value but reuse the same name.This construct is allowed
fn main() {
let spaces = " "; //String type
let spaces = spaces.len(); // Number type
}
let spaces = " "; //String type
let spaces = spaces.len(); // Number type
}
Shadowing thus spares us from having to come up with different names
Error
let mut spaces = " ";
spaces = spaces.len(); // Gives error
spaces = spaces.len(); // Gives error