The let and const keywords in Rust are used to declare variables. However, there are some key differences between the two keywords.
Scope: let variables are scoped to the block in which they are declared, while const variables are scoped to the entire module in which they are declared.
Mutability: let variables are mutable by default, while const variables are immutable.
Initialization: let variables can be initialized with any expression, while const variables must be initialized with a constant expression.
Here is a table that summarizes the differences between let and const:
Feature
let
const
Scope
Block
Module
Mutability
Mutable
Immutable
Initialization
Any expression
Constant expression
Here is an example of how to use let and const:
Rust
fn main() {
// `let` variable.
let x = 5;
// `const` variable.
const Y: i32 = 10;
// The `x` variable can be mutated.
x = 10;
// The `Y` variable cannot be mutated.
// Y = 20; // This will compile an error.
}
In this example, the x variable is declared using the let keyword and initialized with the value 5. The Y variable is declared using the const keyword and initialized with the value 10. The x variable can be mutated, while the Y variable cannot be mutated.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The let and const keywords in Rust are used to declare variables. However, there are some key differences between the two keywords.
Here is a table that summarizes the differences between let and const:
Here is an example of how to use let and const:
Rust
In this example, the x variable is declared using the let keyword and initialized with the value 5. The Y variable is declared using the const keyword and initialized with the value 10. The x variable can be mutated, while the Y variable cannot be mutated.