Constant vs Variable in Rust
In this article, we have covered the differences between constant and variable in Rust Programming Language in depth.
The differences between constant and variable in Rust are:
Attribute | Variable | Constant |
---|---|---|
Keyword used | let | const |
Can use mul keyword? | Yes | No |
Immutable | Not always but by default | Always |
Shadowing? | Allowed | Not allowed |
Is Datatype defined? | No | Yes |
- The syntax used to define a variable and constant in Rust are different.
// Syntax of Variable in Rust
let VARIABLE_RUST = value_in_any_datatype;
// Syntax of Constant in Rust
const CONSTANT_RUST::datatype = value_in_given_datatype;
Note the data type is defined in constant but not in case of variable.
-
Variables are immutable by default but can be made mutable by using "mul" keyword while defining a variable. On the other hand, constant is always immutable and cannot be made mutable.
-
Variables are defined using "let" keyword while constants are defined using "const" keyword.
let pie_variable = 3.14159;
const pie_constant::f32 = 3.14159;
- mul keyword is used to make a variable mutable. mul keyword can be used only with variable and cannot be used with constant.
// mutable variable
let mul pie_variable = 3.14159;
// this will give an error
const mul pie_constant::f32 = 3.14159;
- Variables can be shadowed while Constant cannot be shadowed.
In this code, variable COMPANY is
let COMPANY = "opengenus";
let COMPANY = COMPANY.len();
The above code with variable work. Note that the variable is immutable by default.
The same code with constant give an error:
const COMPANY:&str = "opengenus";
// Error
const COMPANY:usize = COMPANY.len();
- Constant can be defined only for constant expression and cannot be the result of an expression that is calculated at run time.
On the other hand, variable can be defined for expressions that are computed during runtime.
With this article at OpenGenus, you must have a strong idea of the differences between constant and variable in Rust. Enjoy.