Rust Constants

Rust Constants – Complete Beginner Guide
Constants are an essential part of writing clean, maintainable Rust code.
They help you:
Store fixed values
Prevent accidental modification
Improve readability
Avoid magic numbers
Write safer programs
If you’re learning Rust, understanding constants is a foundational skill.
In this complete beginner guide, you’ll learn:
What constants are in Rust
How constants differ from variables
How to declare constants
Type requirements
Constants vs static variables
Naming conventions
Best practices
Common mistakes
Real-world examples
Let’s dive in
What Are Constants in Rust?
A constant is a value that cannot change during program execution.
In Rust, constants are declared using the const keyword.
Example:
1 | const MAX_USERS: u32 = 100; |
Once defined, MAX_USERS can never be modified.
Why Constants Matter in Rust
Constants improve code quality by:
- Preventing accidental changes
- Making code more readable
- Eliminating repeated hard-coded values
- Improving maintainability
- Following clean code principles
Instead of writing:
1 | if users > 100 { |
You should write:
1 | if users > MAX_USERS { |
This makes your code self-explanatory.
Basic Syntax of Rust Constants
The syntax for defining a constant is:
1 | const NAME: Type = value; |
Example:
1 2 | const PI: f64 = 3.14159; const MAX_LOGIN_ATTEMPTS: u8 = 5; |
Important rules:
You MUST specify the type.
The name is typically written in ALL_CAPS.
The value must be known at compile time.
Constants vs Variables in Rust
Understanding the difference is crucial.
Variable Example
1 2 | let mut count = 10; count = 15; |
Variables can change (if declared with mut).
Constant Example
1 | const MAX_LIMIT: i32 = 100; |
You cannot modify a constant.
Key Differences
| Feature | Variable | Constant |
|---|---|---|
| Keyword | let | const |
| Mutable | Optional (mut) | Never |
| Type Required | Optional | Required |
| Runtime Assignment | Allowed | Not allowed |
| Compile-Time Value | Not required | Required |
Constants Must Have Explicit Types
This is mandatory in Rust.
Invalid:
1 | const SPEED = 120; |
Correct:
1 | const SPEED: u32 = 120; |
Rust requires type clarity for constants.
Compile-Time Requirement
Constant values must be known at compile time.
Valid:
1 | const SECONDS_IN_MINUTE: u32 = 60; |
Invalid:
1 | const RANDOM_NUMBER: i32 = generate_number(); |
Because function calls are evaluated at runtime (unless const fn).
Constants in Functions
Constants are usually declared outside functions, but they can be inside too.
Example:
1 2 3 4 5 6 7 | fn main() { const TAX_RATE: f64 = 0.18; let price = 100.0; let total = price + (price * TAX_RATE); println!("{}", total); } |
However, most constants are declared globally.
Global Constants in Rust
Constants are often declared at the top of the file.
1 2 3 4 5 | const MAX_USERS: u32 = 1000; fn main() { println!("Maximum users allowed: {}", MAX_USERS); } |
They are accessible anywhere in the same scope.
Constants vs Static Variables
Rust also has static.
They look similar but behave differently.
Constant
1 | const MAX_POINTS: u32 = 100; |
Static Variable
1 | static MAX_POINTS: u32 = 100; |
Key Differences
| Feature | const | static |
|---|---|---|
| Inlined | Yes | No |
| Memory Address | Not fixed | Has fixed address |
| Mutable | Never | Can be with static mut |
| Usage | Compile-time constant | Global memory value |
Use const in most cases.
Use static only when necessary.
Constant Expressions
Rust allows expressions in constants.
Example:
1 2 | const HOURS_IN_DAY: u32 = 24; const MINUTES_IN_DAY: u32 = HOURS_IN_DAY * 60; |
This works because it’s compile-time calculable.
const fn (Advanced but Important)
Rust allows special functions called const fn.
They can be used in constant expressions.
Example:
1 2 3 4 5 | const fn square(x: i32) -> i32 { x * x } const AREA: i32 = square(4); |
This is evaluated at compile time.
Naming Conventions for Constants
Rust follows strict naming conventions.
- Use ALL_CAPS
- Separate words with underscores
Example:
1 2 | const MAX_BUFFER_SIZE: usize = 1024; const DEFAULT_TIMEOUT_SECONDS: u64 = 30; |
Avoid:
1 | const maxBufferSize: usize = 1024; // Bad style |
Real-World Example: Configuration Constants
Example: Web Server Config
1 2 3 4 5 6 7 | const SERVER_PORT: u16 = 8080; const MAX_CONNECTIONS: u32 = 500; const TIMEOUT_SECONDS: u64 = 30; fn main() { println!("Server running on port {}", SERVER_PORT); } |
Using constants makes configuration easy to update.
Avoiding Magic Numbers
Magic numbers are hard-code explaining values.
Bad:
1 | if temperature > 37 { |
Good:
1 2 3 | const FEVER_THRESHOLD: i32 = 37; if temperature > FEVER_THRESHOLD { |
Improves readability instantly.
Constants in Struct Implementations
Example:
1 2 3 4 5 6 7 8 9 | struct Circle; impl Circle { const PI: f64 = 3.14159; fn area(radius: f64) -> f64 { Self::PI * radius * radius } } |
Associated constants are useful in types.
Constants in Modules
1 2 3 | mod config { pub const MAX_USERS: u32 = 1000; } |
Access with:
1 | config::MAX_USERS |
This keeps code organized.
Common Beginner Mistakes
- Forgetting type annotation
- Trying to modify a constant
- Using runtime values
- Using wrong naming convention
- Confusing
constwithstatic
Best Practices for Using Constants in Rust
- Use constants for fixed configuration values
- Avoid magic numbers
- Keep names descriptive
- Use ALL_CAPS naming
- Prefer
constoverstaticunless necessary - Group related constants in modules
Practical Example: Discount Calculator
1 2 3 4 5 6 7 8 | const DISCOUNT_RATE: f64 = 0.2; fn main() { let price = 200.0; let final_price = price - (price * DISCOUNT_RATE); println!("Final price: {}", final_price); } |
If discount changes, update only one line.
Frequently Asked Questions (FAQs)
1. What is a constant in Rust?
A constant is a fixed value declared using the const keyword that cannot be changed during program execution.
2. Do Rust constants require a type?
Yes. Constants must have an explicit type annotation.
3. Can constants be modified?
No. Constants are immutable by default and cannot be change.
4. What is the difference between const and static?
const values are inlined and compile-time evaluated, while static variables have a fixed memory location and may be mutable.
5. Can constants use expressions?
Yes, as long as the expression can be evaluate at compile time.
Final Thoughts
Rust constant are:
Safe
Predictable
Compile-time evaluated
Essential for clean code
They help:
Avoid magic numbers
Improve maintainability
Reduce bugs
Make configuration easier
If you want to write professional Rust code, mastering constant is a must.
