What Are Constants in Rust?

Constants are a special method in Rust to store unchangeable values similar to variables. We all know that regular variables are mutable, such as var, but constants are fixed and known at compile time.

constants make our programs more efficient and safer, so that we can’t modify values accidentally. and it’s widely used for configuration values, mathematical constants, and system settings.

How to Declare a Constant in Rust?

We can use the const keyword to declare a constant in Rust. The constant name is always written in UPPERCASE by convention, and its type must be explicitly stated.

Basic syntax:

const NAME: TYPE = VALUE; => This is a basic format to declare a const in Rust.

  • Const tells Rust it is a constant and can’t be changed.
  • NAME -> This shows the name as a constant in uppercase by rules.
  • TYPE -> It shows the data type of the values.
  • VALUE -> This is our fixed value.
const NAME: TYPE = VALUE;

See this simple constant example:

fan main() {
const MAX_POINTS: u32 = 100_000;
println!("The maximum points allowed: {}", MAX_POINTS);
}
  • In this example, MAX_POINTS is immutable, and the u32 type is required because constants always have an explicit type.
  • You can use an underscore between numbers to easily read big numbers.

Constants Program that calculate the area of a rectangle

fn main() {
    const WIDTH: i32 = 50;
    const HEIGHT: i32 = 30;

    let area = WIDTH * HEIGHT;
    println!("The area of the rectangle is: {} square units", area);
}

Important Rules of Constants In Rust

1) When you declare a constant in Rust, so must write its data type because Rust won’t guess. For example,

const PI: f64 = 3.14159;  // Correct (type is f64)
const PI = 3.14159; // Error (type missing)

See this code, Rust need to know the exact type of constant during compilation so it can optimise the code and avoid mistakes.

2) Always use the compilation values because the compiler can calculate them before the program runs.

For example:

const SECONDS_IN_HOUR: u32 = 60 * 60;  // Compiler can calculate 3600 

const NOW: u32 = get_current_time(); // Compiler can’t know this before running

3) You can use constants outside of the functions and making them usable anywhere in your program.

const APP_NAME: &str = "MyRustApp";

fn main() {
println!("Welcome to {}", APP_NAME);
}

Constant Multiple Uses Example

const TAX_RATE: f64 = 0.18;

fn main() {
let price_item1 = 100.0;
let price_item2 = 250.0;

let total = price_item1 + price_item2;
let tax = total * TAX_RATE;

println!("Total Price: {}", total);
println!("Tax to Pay: {}", tax);
}
  • You can cee, we can use constant in multiple calculations.

Real-Life Example: Monthly Travel Expense Calculator

const BUS_FARE_PER_RIDE: u32 = 15;   // Cost per bus ride in local currency
const RIDES_PER_DAY: u32 = 2; // To college and back
const DAYS_IN_MONTH: u32 = 26; // College open days in a month

fn main() {
let total_rides = RIDES_PER_DAY * DAYS_IN_MONTH;
let total_expense = BUS_FARE_PER_RIDE * total_rides;

println!("Total Bus Rides in a Month: {}", total_rides);
println!("Total Travel Expense: {} currency units", total_expense);
}

This code is useful for counting the money spent on bus travel. Copy and run this code to check how it works.

Why Use Constants In Rust?

  • Constants avoid bugs because their values are not changeable.
  • Rust can optimise the program for speed because constants are evaluated at compile time.
  • We can use the same constant value across multiple functions without extra writes.

Exercise For Your Understanding:

  1. Create a Rust program where you declare a constant DAYS_IN_WEEK = 7.
  2. Use a constant to calculate how many days are in 10 weeks and print the result.

Leave a Comment