[フレーム]

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:

Example

const BIRTHYEAR: i32 = 1980;
const MINUTES_PER_HOUR: i32 = 60;
Try it Yourself »

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:

Example

const BIRTHYEAR: i32 = 1980; // Ok
const BIRTHYEAR = 1980; // Error: missing type
Try it Yourself »

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:

Feature Constant (const) Variable (let)
Can change? No Yes, if mut is used
Type required? Yes No (optional)

Track your progress - it's free!
×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

FORUM ABOUT ACADEMY
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.

AltStyle によって変換されたページ (->オリジナル) /