0
0
Rustprogramming~3 mins

Why Constants in Rust? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could fix one number and change your whole program instantly?

The Scenario

Imagine you are writing a program that uses the value of pi many times. You type 3.14159 everywhere by hand.

The Problem

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.

The Solution

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.

Before vs After
Before
let area = 3.14159 * radius * radius;
let circumference = 2.0 * 3.14159 * radius;
After
const PI: f64 = 3.14159;
let area = PI * radius * radius;
let circumference = 2.0 * PI * radius;
What It Enables

Constants make your code clearer, safer, and easier to change without hunting for repeated values.

Real Life Example

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.

Key Takeaways

Constants store fixed values with names.

They prevent mistakes from repeated numbers.

Changing a constant updates all uses automatically.