Constants in Rust are immutable values that are bound to a name and cannot change throughout the program's execution. They play a crucial role in creating efficient and maintainable code.
In Rust, constants are declared using the const
keyword. They must always have an explicit type annotation and their value must be a constant expression that can be determined at compile time.
const MAX_POINTS: u32 = 100_000;
Constants are useful for defining values that remain unchanged throughout your program. They can help improve code readability and maintainability. Here's an example:
const PI: f64 = 3.14159;
fn calculate_area(radius: f64) -> f64 {
PI * radius * radius
}
fn main() {
let area = calculate_area(5.0);
println!("The area is: {}", area);
}
While constants may seem similar to Rust variables, they have some key differences:
Aspect | Constants | Variables |
---|---|---|
Mutability | Always immutable | Can be mutable or immutable |
Type annotation | Always required | Optional in many cases |
Scope | Can be global or local | Local to their scope |
Naming convention | SCREAMING_SNAKE_CASE | snake_case |
Rust also supports associated constants, which are constants associated with a type. They are defined within an struct, enum, or trait implementation.
struct Circle {
radius: f64,
}
impl Circle {
const PI: f64 = 3.14159;
fn area(&self) -> f64 {
Self::PI * self.radius * self.radius
}
}
fn main() {
let circle = Circle { radius: 5.0 };
println!("Area: {}", circle.area());
println!("PI: {}", Circle::PI);
}
Associated constants provide a way to namespace constants within a type, enhancing code organization and readability.
Constants are a fundamental feature in Rust, offering a way to define immutable values that can be used throughout your program. By understanding and effectively using constants, you can write more maintainable and efficient Rust code.
For more information on related topics, explore Rust data types and Rust ownership concept.