Rust Constants

Rust Tutorial

🦀 Rust Constants

In Rust, constants are fixed values that never change during program execution. They are evaluated at compile time and help make code safer, faster, and easier to understand.

🔹 1. Declaring Constants (const)

const MAX_USERS: u32 = 100;

fn main() {
println!(“{}”, MAX_USERS);
}

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:

const PI: f64 = 3.14159;
const APP_NAME: &str = "RustApp";
const TIMEOUT: u64 = 30;

🔹 3. Constants vs Variables

let x = 10; // variable
// x = 20; // ❌ not allowed (immutable)
const Y: i32 = 10;
// Y = 20; // ❌ never allowed

🔹 4. Constants Are Global or Local

Constants can be declared outside or inside functions.

const VERSION: &str = "1.0";

fn main() {
const MAX_RETRY: u8 = 3;
println!(“{}”, MAX_RETRY);
}


🔹 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 APP_PORT: u16 = 8080;

⚠️ static is advanced and used when a fixed memory address is required.


🔹 6. Constant Expressions

Allowed:

const A: i32 = 10 + 20;
const B: i32 = A * 2;

Not allowed:

// const C: i32 = get_value(); ❌ function call

🔹 7. Using Constants in Match & Arrays

const LIMIT: i32 = 5;

fn main() {
let arr = [0; LIMIT as usize];
println!(“{:?}”, arr);
}


🔑 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

You may also like...