bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Rust/Rust Tutorial
Rust•Rust Tutorial

Rust Constants

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Rust Constants?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ BIRTHYEAR: i32 = 1980;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Constants vs Variables
Constants Must Have a Type
Creating a Constant

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