What Are Constants in Rust?
Constants in Rust allow you to define fixed values (immutable values) that do not change during the program’s execution.
Constants are always immutable. you cannot change their value after they are defined.
Constants are extremely useful when you need a value to remain the same throughout into your code.
Constants are immutable values whose type must be explicitly defined. Unlike variables, constants are evaluated at compile time, meaning their values are hard-coded and cannot be altered during runtime.
- Constants are defined using the const keyword.
- Constants can be used anywhere in the program.
- Their values must have a fixed type and they can only hold data that can be computed at compile time.
Characteristics of Constants
- Immutable:
- Constants are always immutable. You cannot modify their value after definition.
- Global Scope:
- Constants are accessible throughout the program as long as they are in scope.
- Static Lifetime:
- Constants exist for the duration of the program.
- Explicit Type Annotation:
- The type of a constant must be explicitly specified.
- Compile-Time Evaluation:
- The value of a constant must be a constant expression that the compiler can evaluate the value.
Syntax of Constants
The syntax for defining a constant in Rust is the:
const CONSTANT_NAME: DATA_TYPE = VALUE;
Example: Defining a Constant
fn main() {
const PI: f64 = 3.14159; // Constant for the value of Pi
const MAX_USERS: u32 = 100; // Maximum number of users allowed
println!("Value of PI: {}", PI);
println!("Maximum Users Allowed: {}", MAX_USERS);
}
What Is f64 and u32 In Rust?
In Rust, specifying the type (like f64 and u32) for constants is required Because:
- Constants are evaluated at compile time, not runtime.
- Rust needs to know the exact type to allocate memory and perform operations safely.
- Without the type, the compiler throws an error.
Example:
const PI: f64 = 3.14159; // f64 for floating-point number
const MAX_USERS: u32 = 100; // u32 for unsigned 32-bit integer
If you try to write code without the type:
const PI = 3.14159;
const MAX_USERS = 100;
The compiler will give an error:
“missing type for const item”
On the other hand, for variables (using let) keyword, type annotations are usually optional because Rust can infer the type:
let pi = 3.14159; // Type inferred as f64
let max_users = 100; // Type inferred as i32
So, for constants — yes, you must specify the type!
Key Points About Constants
Constants Must Have a Fixed Type
- Unlike variables where type inference is allowed, constants require explicit type annotations.
const MESSAGE: &str = "Hello, Rust!";
You cannot reassign a value to a constant.
Constants Are Not Variables
- Constants differ from variables. they are evaluated at compile time, while variables can be mutable and are evaluated at runtime.
Global Constants
- Constants can be defined outside the main function or any other function. also making them globally accessible.
const API_KEY: &str = "1234-5678-ABCD";
fn main() {
println!("API Key: {}", API_KEY);
}
Difference Between const and let
Feature | const | let |
---|---|---|
Mutability | Always immutable | Mutable with mut keyword |
Type Annotation | Mandatory | Optional (type inference allowed) |
Evaluation Time | Compile-time | Runtime |
Scope | Can be global or local | Block-specific |
Practical Use Cases of Constants
Defining Mathematical Constants
const E: f64 = 2.71828;
const GOLDEN_RATIO: f64 = 1.61803;
Application Settings
const MAX_CONNECTIONS: u32 = 50;
const SERVER_PORT: u16 = 8080;
Error Messages or Fixed Strings
const ERROR_MESSAGE: &str = "An unexpected error occurred!";
Common Mistakes and Solutions
Forgetting Type Annotation
- Error: missing type for const item.
- Solution: Always specify the type explicitly when defining constants.
const MY_CONSTANT = 10; // Error
const MY_CONSTANT: i32 = 10; // Correct
Using Non-Constant Expressions
- Error: expected constant, found a runtime value.
- Solution: Ensure that the value assigned to the constant is evaluable at compile time.
const VALUE: i32 = some_function(); // Error
fn some_function() -> i32 {
5
}
Coding Exercise
- Define a constant LIGHT_SPEED with the value 299_792_458 and print it in the main function.
- Create a constant APP_NAME with a string value and use it in multiple functions to display application details.
Complete Example: Using Constants in a Program
const GREETING: &str = "Welcome to Rust Programming!";
const VERSION: f32 = 1.0;
const MAX_ITEMS: u32 = 500;
fn main() {
println!("{}", GREETING);
println!("Version: {}", VERSION);
println!("Maximum allowed items: {}", MAX_ITEMS);
}