Rust Constants

Defining unchangeable values in Rust programs

🔐 What are Rust Constants?

Constants in Rust are values that never change throughout the program's execution. They're declared with 'const' keyword, must have explicit types, and are evaluated at compile time for optimal performance.


// Declaring constants
const MAX_POINTS: u32 = 100_000;
const PI: f64 = 3.14159;
const APP_NAME: &str = "My Rust App";
                                    
Constant Features

Constant Characteristics

🚫

Immutable Always

Constants can never be made mutable

const SPEED: u32 = 300;
// Cannot use 'mut' with const
🌍

Global Scope

Can be declared in any scope

const GLOBAL_MAX: i32 = 1000;

fn main() {
    const LOCAL_MIN: i32 = 0;
}

Compile Time

Values computed at compile time

const SECONDS_IN_HOUR: u32 = 60 * 60;
const AREA: f64 = 3.14 * 5.0 * 5.0;
🏷️

Type Required

Must always specify the type

const COUNT: usize = 42;
const NAME: &str = "Rust";

🔹 Declaring Constants

Constants must be declared with explicit types and constant expressions:

// Global constants
const MAX_USERS: u32 = 1000;
const COMPANY_NAME: &str = "TechCorp";
const TAX_RATE: f64 = 0.08;

fn main() {
    // Local constants
    const BUFFER_SIZE: usize = 1024;
    const IS_DEBUG: bool = true;
    
    println!("Max users: {}", MAX_USERS);
    println!("Company: {}", COMPANY_NAME);
    println!("Tax rate: {}%", TAX_RATE * 100.0);
    println!("Buffer size: {} bytes", BUFFER_SIZE);
    println!("Debug mode: {}", IS_DEBUG);
}

Output:

Max users: 1000

Company: TechCorp

Tax rate: 8%

Buffer size: 1024 bytes

Debug mode: true

🔹 Constants vs Variables

Understanding the key differences between constants and variables:

const FIXED_VALUE: i32 = 100;  // Constant - never changes

fn main() {
    // Immutable variable
    let immutable_var = 50;
    
    // Mutable variable
    let mut mutable_var = 25;
    mutable_var = 75;  // Can be changed
    
    // Constants are always accessible
    println!("Constant: {}", FIXED_VALUE);
    println!("Immutable variable: {}", immutable_var);
    println!("Mutable variable: {}", mutable_var);
    
    // This would cause an error:
    // FIXED_VALUE = 200;  // Cannot assign to constant
    // immutable_var = 60; // Cannot assign to immutable variable
}

Output:

Constant: 100

Immutable variable: 50

Mutable variable: 75

🔹 Constant Expressions

Constants can only be set to constant expressions, not function results:

// Valid constant expressions
const MINUTES_IN_HOUR: u32 = 60;
const SECONDS_IN_HOUR: u32 = MINUTES_IN_HOUR * 60;
const CIRCLE_AREA: f64 = 3.14159 * 10.0 * 10.0;

// Mathematical constants
const E: f64 = 2.71828;
const GOLDEN_RATIO: f64 = 1.618;

fn main() {
    println!("Minutes in hour: {}", MINUTES_IN_HOUR);
    println!("Seconds in hour: {}", SECONDS_IN_HOUR);
    println!("Circle area: {:.2}", CIRCLE_AREA);
    println!("Euler's number: {}", E);
    println!("Golden ratio: {}", GOLDEN_RATIO);
    
    // These would NOT work as constants:
    // const CURRENT_TIME = std::time::SystemTime::now(); // Function call
    // const RANDOM_NUM = rand::random::();          // Function call
}

Output:

Minutes in hour: 60

Seconds in hour: 3600

Circle area: 314.16

Euler's number: 2.71828

Golden ratio: 1.618

🔹 Naming Conventions

Rust constants follow specific naming conventions:

// Correct naming: SCREAMING_SNAKE_CASE
const MAX_CONNECTION_POOL_SIZE: usize = 100;
const DEFAULT_TIMEOUT_SECONDS: u64 = 30;
const API_BASE_URL: &str = "https://api.example.com";
const IS_PRODUCTION_MODE: bool = false;

// Configuration constants
const DATABASE_HOST: &str = "localhost";
const DATABASE_PORT: u16 = 5432;
const CACHE_EXPIRY_MINUTES: u32 = 15;

fn main() {
    println!("Pool size: {}", MAX_CONNECTION_POOL_SIZE);
    println!("Timeout: {} seconds", DEFAULT_TIMEOUT_SECONDS);
    println!("API URL: {}", API_BASE_URL);
    println!("Production: {}", IS_PRODUCTION_MODE);
    println!("DB: {}:{}", DATABASE_HOST, DATABASE_PORT);
    println!("Cache expires in {} minutes", CACHE_EXPIRY_MINUTES);
}

Output:

Pool size: 100

Timeout: 30 seconds

API URL: https://api.example.com

Production: false

DB: localhost:5432

Cache expires in 15 minutes

🧠 Test Your Knowledge

Which keyword is used to declare constants in Rust?