- Rust Essentials(Second Edition)
- Ivo Balbaert
- 514字
- 2021-07-02 15:30:38
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.
- Microsoft Application Virtualization Cookbook
- 用戶體驗增長:數字化·智能化·綠色化
- MATLAB for Machine Learning
- MongoDB,Express,Angular,and Node.js Fundamentals
- Python開發基礎
- Arduino機器人系統設計及開發
- Scratch從入門到精通
- Appcelerator Titanium:Patterns and Best Practices
- Modernizing Legacy Applications in PHP
- 超好玩的Scratch 3.5少兒編程
- Python面試通關寶典
- HTML并不簡單:Web前端開發精進秘籍
- Java面試一戰到底(基礎卷)
- Mastering Machine Learning with scikit-learn
- Computer Vision with Python 3