Static and Constant Variables

์ „์—ญ ์ƒํƒœ(state) ์ •์  ๋ณ€์ˆ˜์™€ ์ƒ์ˆ˜๋กœ ๊ด€๋ฆฌ๋ฉ๋‹ˆ๋‹ค.

Global state is managed with static and constant variables.

const

์ปดํŒŒ์ผ ์‹œ์ ์˜ ์ƒ์ˆ˜๋ฅผ ์„ ์–ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

You can declare compile-time constants:

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:

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.