1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-04-21 23:45:42 +02:00
comprehensive-rust/src/basic-syntax/static-and-const.md

40 lines
824 B
Markdown
Raw Normal View History

2022-12-21 16:36:30 +01:00
# Static and Constant Variables
2022-12-21 09:31:53 -08:00
Global state is managed with static and constant variables.
2022-12-21 16:36:30 +01:00
## `const`
You can declare compile-time constants:
```rust,editable
const DIGEST_SIZE: usize = 3;
const ZERO: Option<u8> = Some(42);
fn compute_digest(text: &str) -> [u8; DIGEST_SIZE] {
let mut digest = [ZERO.unwrap_or(0); DIGEST_SIZE];
for (idx, &b) in text.as_bytes().iter().enumerate() {
digest[idx % DIGEST_SIZE] = digest[idx % DIGEST_SIZE].wrapping_add(b);
}
digest
}
fn main() {
let digest = compute_digest("Hello");
println!("Digest: {digest:?}");
}
```
## `static`
You can also declare static variables:
```rust,editable
static BANNER: &str = "Welcome to RustOS 3.14";
fn main() {
println!("{BANNER}");
}
```
We will look at mutating static data in the chapter on Unsafe Rust.