O'Reilly logo

Rust Essentials by Ivo Balbaert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Global constants

Often, an application needs a few values that are in fact constants; they do not change in the course of the program. For example: the name of our game, which is "Monster Attack", is a constant, as is the maximum value of health, which is the number 100. We must be able to use them in main() or any other function in our program, so they are placed at the top of the code file. They live in the global scope of the program. Such constants are declared with the static keyword as follows:

// see Chapter 2/code/constants1.rs
static MAX_HEALTH: i32 = 100;
static GAME_NAME: &'static str = "Monster Attack";

fn main() {
}

Names of constants must be in uppercase and underscores can be used to separate words. Their type must also be indicated; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required