bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths
Learn/Rust/Rust Tutorial
Rust•Rust Tutorial

Rust Constants

Constants

Constant variables are used to store values that never change.

Unlike regular variables, constants must be defined with a type (e.g. i32 or char ).

Creating a Constant

To create a constant, use the const keyword, followed by the name, type, and value:

const BIRTHYEAR: i32 = 1980;
const
MINUTES_PER_HOUR: i32 = 60;

Constants Must Have a Type

You must write the type when creating a constant. You cannot let Rust guess the type like you can with regular variables:

const BIRTHYEAR: i32 = 1980; // Ok
const BIRTHYEAR = 1980; // Error: missing type

Naming Rules

Another thing about constants, is that it is considered good practice to declare them with uppercase.

It is not required, but useful for code readability and common for Rust programmers:

Examples

  • MAX_SPEED
  • PI
  • MINUTES_PER_HOUR

Constants vs Variables

Here's a quick comparison

FeatureConstant ( const )Variable ( let )
Can change?NoYes, if mut is used
Type required?YesNo (optional)

Previous

Rust Data Types

Next

Rust Operators

This chapter

Overview
20

Lessons

46m

Read time

1. Rust Tutorial2. Rust Introduction3. Rust Get Started4. Rust Syntax5. Rust Output (Print Text)6. Rust Comments7. Rust Variables8. Rust Data Types9. Rust Constants10. Rust Operators11. Rust Booleans12. Rust If .. Else Conditions13. Rust Match14. Rust Loops15. Rust While Loops16. Rust For Loop17. Rust Functions18. Rust Scope19. Rust Strings20. Rust Ownership

On this page

ConstantsCreating a ConstantConstants Must Have a TypeNaming RulesConstants vs Variables