Constant values are mainly useful when you need to define a variable that does need to be changed by other parts of the program. Unlike immutable variables, constant variables in Rust cannot be made mutable even using the mut keyword.
Rust Constants
There are two types of constants in Rust:
- Global constants – These are unchangeable values that all program parts can use globally.
- Static constants – These constants are mutable but contain a static lifetime. The static lifetime is inferred automatically and does not need to be annotated.
We will not concern ourselves with static constants for this tutorial.
Rust Declare Constant Variable
To declare a constant variable in rust, we use the const keyword followed by the name of the variable and its type.
The syntax is as shown:
Note that you must explicitly specify the type of a constant variable, unlike normal variables in Rust.
According to the Rust rules of naming, a constant variable should have a screaming snake casing as:
The example below shows how to define a constant variable called PI.
fnmain() {
let radius = 7.141;
println!("Area of the cirlce: {} cm2", PI*radius*radius);
}
Once declared, we can use the constant variable in any part of the program.
Area of the cirlce: 160.20200192305325 cm2
Note that the compiler will return an error if we attempt to change the value of a constant variable. An example is as shown below:
fnmain() {
PI = 3.141;
let radius = 7.141;
println!("Area of the cirlce: {} cm2", PI*radius*radius);
}
The code above should return an error as we try to modify the value of a constant variable.
Conclusion
In this article, we covered how to create and use constant variables. Consts are very useful for setting global variables that would result in unexpected behavior if changed.