What if you could fix one number and change your whole program instantly?
Why Constants in Rust? - Purpose & Use Cases
Imagine you are writing a program that uses the value of pi many times. You type 3.14159 everywhere by hand.
Typing the same number repeatedly is slow and easy to make mistakes. If you want to change pi's value, you must find and fix every spot manually.
Constants let you store a fixed value once with a name. You use the name everywhere, so the value stays the same and is easy to update.
let area = 3.14159 * radius * radius; let circumference = 2.0 * 3.14159 * radius;
const PI: f64 = 3.14159; let area = PI * radius * radius; let circumference = 2.0 * PI * radius;
Constants make your code clearer, safer, and easier to change without hunting for repeated values.
In a game, you can define a constant for the maximum player health. If you want to change it later, you update one place, and the whole game uses the new value.
Constants store fixed values with names.
They prevent mistakes from repeated numbers.
Changing a constant updates all uses automatically.