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.