0
0
Rustprogramming~5 mins

Constants in Rust

Choose your learning style9 modes available
Introduction

Constants hold values that never change while the program runs. They help keep important values safe and clear.

When you have a value like pi that should stay the same everywhere.
To set fixed limits like maximum score or timeout duration.
When you want to give a name to a number or text to make your code easier to read.
To avoid repeating the same value in many places, so you can change it once if needed.
When you want to prevent accidental changes to important values.
Syntax
Rust
const NAME: Type = value;

Constants must have their type declared.

They are always immutable and live for the entire program.

Examples
Defines a constant named MAX_POINTS with the value 100 of type unsigned 32-bit integer.
Rust
const MAX_POINTS: u32 = 100;
Defines a constant string slice named GREETING with the value "Hello!".
Rust
const GREETING: &str = "Hello!";
Sample Program

This program defines a constant PI and prints its value. The constant cannot be changed later.

Rust
const PI: f64 = 3.14159;

fn main() {
    println!("The value of PI is {}", PI);
}
OutputSuccess
Important Notes

Constants are different from variables because they cannot be changed after being set.

Use uppercase letters with underscores for constant names by convention.

Constants can be used anywhere in your code, even outside functions.

Summary

Constants store fixed values that do not change.

They require a type and are always immutable.

Use constants to make your code clearer and safer.