Constants are fixed variable values that never be changed. Once a variable is declared as constant, its value will never be reassigned or changed.
const keyword used to create a constant in Rust.
Rust Constant
Here is a syntax for constant declaration in Rust.
const variable:dataType = value;
const is a keyword the variable is a valid variable name in Rust DataType is a Valid data type in Rust Value is data literal.
Here is an example
fn main() {
const NUMBER: i32 = 20;
const FLOATING_NUMBER: f32 = 20.0;
println!("{}", NUMBER);
println!("{}", FLOATING_NUMBER);
}
Output:
20
20
Rust Constant naming conventions
Constant variables can be named with the following conventions
- Constants’ names are in UPPERCASE with snake_case by convention
- Rust identifier can not be used as a constant names
- Valid characters allowed are Letters, Digits, and Underscore(
_
) - Digits must not start with a constant name
What is the difference between constant and variable?
Following are the differences between constant and variable.
Constant | Variable |
---|---|
these are declared with const keyword | declared with let keyword |
Constants must have a datatype | variables type is optional and inferred from its value |
duration | time in milliseconds shown before disappearing from the page |
constant once declared, its value never be changed | variables by default immutable not change its value, you change its value using mut keyword |
horizontalPosition | Horizontal position - ‘start’, ‘center’, ’end’, ’left’, ‘right’ |
Shadowing is not possible | shadowing is possible |
Constants can be used in global and block scope | Variables also follow lexical scope |
Constant shadowing
Shadowing makes variables change their value and type.
One variable is declared and assigned with a type, You can reassign it with a new type, and its value In the below example, the variable name is declared of type &str. Reassigned this variable with a new type of value. Here is a valid code
fn main() {
const NAME: &str = "John"; // valid
println!("{}", NAME);
const NAME: i32 = 123; // not valid, assigned with new datatype and value
println!("{}", NAME);
}
It throws the compilation error NAME
must be defined only once in the value namespace of this block