Getting to Know Rust: Constants

The journey to proficiency in Rust continues. In a previous article, I provided a brief overview of how to get started with Rust by creating our first "Hello, World!" program.

This article will focus on a specific language aspect, namely constants.

What is a Constant?

A constant is a value that you bind to a name, similar to a variable. By its nature, the value cannot change. Unlike regular variables, constants are evaluated at compile time, which means Rust figures out their value before your program even runs. This makes them incredibly useful for performance-critical code.

What is the Purpose of a Constant?

Constants are useful in any programming language because they help you avoid so-called "magic values"—those mysterious numbers or strings hardcoded throughout your codebase. You've probably seen this problem before: a value gets scattered across a million different locations, making it nearly impossible to update consistently when things change.

Instead of hardcoded values, declaring a handful of constants upfront makes your intentions crystal clear and updates painless. Change the constant once, and the new value propagates everywhere it's used.

Declaring Constants

Here's how to declare the speed of light (in metric) as a constant in Rust:

const SPEED_OF_LIGHT: u32 = 299792458

First, the const keyword is used, followed by a name. The convention is all caps—this signals to anyone reading your code that this is a constant and its value won't change. Next, the constant must receive a type annotation; I've used a 32-bit unsigned integer type. The last step is to bind the value to the new constant with the = operator.

Scope of Validity

Constants can be declared in any scope, including the global scope, making them widely available throughout your program. You'll often see constants declared at the module or crate level so they're accessible wherever they're needed.

Other Considerations

As one might expect, constants are immutable by default—their values can't be changed, and you can't use the mut keyword with them.

You might be wondering: what's the difference between a constant and an immutable variable? Great question! A key concept in Rust is that variables are immutable by default. You must expressly choose to make them mutable (changeable) by adding the mut keyword to the variable binding. However, there's an important distinction: constants are evaluated at compile time and can't be shadowed, while immutable variables declared with let are evaluated at runtime and can be shadowed. For most cases, if you need a value that truly never changes, a constant is the right choice.

Conclusion

Constants might seem like a small feature, but they're one of those foundational tools that make your code clearer and easier to maintain. As you continue your Rust journey, you'll find yourself reaching for them again and again. Happy coding!

References: