Global constants
Often, an application needs a few values that are in fact constants, meaning that they do not change in the course of the program. In our game, for example, the game name Monster Attack could be a constant, as could the maximum health amount, which is the number 100. We must be able to use them in the main() function 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 keyword static, as follows:
// see Chapter 2/code/constants1.rs static MAX_HEALTH: i32 = 100; static GAME_NAME: &str = "Monster Attack"; fn main() { }
Names of constants must be in uppercase, underscores can be used to separate word parts. Their type must also be indicated; the variable MAX_HEALTH is a 32-bit integer (i32) and the variable GAME_NAME is a string (str) type. As we will discuss further, the declaration of types for variables is done in exactly the same way, although it is often optional when the compiler can infer the type from the code context.
Remember that Rust is a low-level language, so many things must be specified in detail. The & is a reference to something (it contains its memory address), here of the string.
The compiler gives us a warning, which looks like this:
warning: static item is never used: `MAX_HEALTH`, #[warn(dead_code)] on by default
This warning does not prevent the compilation, so in this stage, we can compile to an executable constants1.exe. But the compiler is right; these objects are never used in the program's code (they are called dead code), so, in a complete program, either use them or throw them out.
Besides static values, we can also use simple constant values whose value never changes. Constants always have to be typed, as shown here:
const MYPI: f32 = 3.14;
The compiler automatically substitutes the value of the constant everywhere in the code.