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:

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:

Output:

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:

Trying to use mut:

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?