Like in almost all other programming languages, variables are single pieces of data that can be stored in memory when a program is running, and may have the potential to change in value during runtime.
Variables need to be given a written alias before assignment:
let variable_name = ...;
As seen above, Rust variables are typically defined using the keyword let, followed by an alphanumeric alias.
Rust does not allow for unassigned variables that are not explicitly typed:
fn main() {
let variable_name;
}
error[E0282]: type annotations needed
--> src/main.rs:2:9
|
2 | let variable_name;
|
|
help: consider giving `variable_name` an explicit type
|
2 | let variable_name: /* Type */;
|
For more information about this error, try `rustc --explain E0282`.
error: could not compile `playground` (bin "playground") due to 1 previous error
fn main() {
let variable_name: char;
}
The "char" after the colon in the above example is not the value of the variable, but the data type.
Exercise:
Try defining a variable of your own with the data type char:
In Rust, explicit types for variables are specified after the variable name, separated from it by a colon, after which the actual value is specified with an equals sign:
fn main() {
let variable_name: char = 'b';
}
Rust's data types will be explained in more detail later in this chapter.