Rust Constants
🦀 Rust Constants
🔹 1. Declaring Constants (const)
Rules for const
-
Must be immutable
-
Type annotation is mandatory
-
Name should be in UPPER_SNAKE_CASE
-
Value must be a compile-time constant
🔹 2. Why Use Constants?
✔ Prevent accidental modification
✔ Improve code readability
✔ Better performance (known at compile time)
✔ Ideal for configuration values
Examples:
🔹 3. Constants vs Variables
🔹 4. Constants Are Global or Local
Constants can be declared outside or inside functions.
🔹 5. Constants vs Static Variables
| Feature | const |
static |
|---|---|---|
| Evaluated | Compile time | Runtime |
| Memory | Inlined | Fixed memory location |
| Mutability | ❌ | ❌ (default) |
| Type required | ✔ | ✔ |
| Lifetime | No fixed address | Entire program |
Example static:
⚠️ static is advanced and used when a fixed memory address is required.
🔹 6. Constant Expressions
Allowed:
Not allowed:
🔹 7. Using Constants in Match & Arrays
🔑 Best Practices
✔ Use const for fixed values
✔ Prefer constants over magic numbers
✔ Use clear, descriptive names
✔ Avoid unnecessary static usage
🧠 Summary
-
const= compile-time constant -
Always immutable
-
Type must be specified
-
Safer than variables
