Rust Constants

When you’re programming in Rust, sometimes you want values that should never change during the execution of your program. For example, mathematical constants like π (pi), or configuration values like the maximum number of connections allowed. In these cases, you can use Rust constants.

What Are Constants? #

  • A constant is a value bound to a name that is always immutable (you can’t change it).
  • You declare constants using the const keyword, not let.
  • Constants are evaluated at compile time.

Unlike variables:

  • You cannot use mut with constants.
  • You must specify the type of a constant.
  • By convention, constants are written in ALL_CAPS_WITH_UNDERSCORES.

Defining Constants #

Here’s the syntax for defining a constant in Rust:

const MAX_POINTS: u32 = 100_000;
Code language: JavaScript (javascript)

Explanation:

  • const → keyword to declare a constant.
  • MAX_POINTS → name of the constant (uppercase by convention).
  • u32 → type annotation (required).
  • 100_000 → value (using underscores makes big numbers easier to read).

Constants vs. Variables #

FeatureVariables (let)Constants (const)
MutabilityImmutable by default, can be mutable with mutAlways immutable
Type annotationOptional (Rust can infer)Required
EvaluationAt runtimeAt compile time
Naming conventionsnake_case (my_variable)UPPER_CASE (MY_CONSTANT)
Keywordletconst

Using Constants Example #

The following example shows how to use constants:

const PI: f64 = 3.14159;
const SECONDS_IN_MINUTE: u32 = 60;

fn main() {
    let radius = 5.0;
    let area = PI * radius * radius;

    println!("Circle area = {}", area);
    println!("One minute has {} seconds.", SECONDS_IN_MINUTE);
}
Code language: Rust (rust)

Output:

Circle area = 78.53975
One minute has 60 seconds.

Where Can You Use Constants? #

Constants are useful when:

  • You need a value used in multiple places.
  • The value should never change.
  • The value is known at compile time.

Examples:

  • Conversion factors (SECONDS_IN_HOUR, BYTES_IN_KB).
  • Fixed limits (MAX_USERS, MAX_CONNECTIONS).
  • Mathematical constants (PI, E).

Common Mistakes with Constants #

Forgetting the type annotation:

const PI = 3.14; // ERROR: missing type
Code language: JavaScript (javascript)

Trying to use mut:

const mut LIMIT: u32 = 10; // ERROR: constants can't be mutable
Code language: JavaScript (javascript)

Summary #

  • Use const when you want values that never change.
  • Constants are different from variables:
    • Always immutable.
    • Type annotation required.
    • Known at compile time.
  • By convention, name them in UPPER_CASE.
Was this Helpful ?