3
The declaration of immutable variables
In Rust if you want to declare a variable, we use the keyword let
.
Example:
fn main() {
let site_name = "Stack Overflow em Português";
println!("{}",site_name);
}
Upshot:
Stack Overflow em Português
This kind of statement creates a immutable variable which, when amended, gives rise to errors.
Example:
fn main() {
let site_name = "Stack Overflow em Português";
println!("{}",site_name);
site_name = "Stack Overflow em Português META";
println!("{}",site_name);
}
Raises this error:
error[E0384]: cannot assign twice to immutable variable `site_name`
--> src/main.rs:4:5
|
2 | let site_name = "Stack Overflow em Português";
| ---------
| |
| first assignment to `site_name`
| help: consider making this binding mutable: `mut site_name`
3 | println!("{}",site_name);
4 | site_name = "Stack Overflow em Português META";
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable
error: aborting due to previous error
For more information about this error, try `rustc --explain E0384`.
While executing rustc --explain E0384
, it is explained that by default variables in Rust are immutable. To correct this error, one must add keyword mut
after let
when declaring the variable. See more.
The declaration of constants
Rust also has a specialized keyword for declaring constants, const
.
Example:
fn main() {
const SITE_NAME: &str = "Stack Overflow em Português";
println!("{}",SITE_NAME);
}
Upshot:
Stack Overflow em Português
As with the example of immutable variables, the attempt of constant retribution will generate errors:
Example:
fn main() {
const SITE_NAME: &str = "Stack Overflow em Português";
println!("{}",SITE_NAME);
SITE_NAME = "Stack Overflow em Português META";
println!("{}",SITE_NAME);
}
Upshot:
error[E0070]: invalid left-hand side of assignment
--> src/main.rs:4:15
|
4 | SITE_NAME = "Stack Overflow em Português META";
| --------- ^
| |
| cannot assign to this expression
error: aborting due to previous error
For more information about this error, try `rustc --explain E0070`.
When executing rustc --explain E0070
, The explanation arises of which left side of an assignment operator should be a place expression. A place expression represents a memory location and can be a variable (with optional namespacing), a melt, an index expression, or a reference field. See more.
The question
Before the information gathered above I ask:
In Rust what are the differences between constants declared with const
and immutable variables declared with let
?