3 Rust has a way of defining constants with the `const` keyword:
9 Unlike [`let`][let] bindings, you must annotate the type of a `const`.
11 [let]: variable-bindings.html
13 Constants live for the entire lifetime of a program. More specifically,
14 constants in Rust have no fixed address in memory. This is because they’re
15 effectively inlined to each place that they’re used. References to the same
16 constant are not necessarily guaranteed to refer to the same memory address for
21 Rust provides a ‘global variable’ sort of facility in static items. They’re
22 similar to constants, but static items aren’t inlined upon use. This means that
23 there is only one instance for each value, and it’s at a fixed location in
32 Unlike [`let`][let] bindings, you must annotate the type of a `static`.
34 Statics live for the entire lifetime of a program, and therefore any
35 reference stored in a constant has a [`'static` lifetime][lifetimes]:
38 static NAME: &'static str = "Steve";
41 [lifetimes]: lifetimes.html
45 You can introduce mutability with the `mut` keyword:
48 static mut N: i32 = 5;
51 Because this is mutable, one thread could be updating `N` while another is
52 reading it, causing memory unsafety. As such both accessing and mutating a
53 `static mut` is [`unsafe`][unsafe], and so must be done in an `unsafe` block:
56 # static mut N: i32 = 5;
67 Furthermore, any type stored in a `static` must be `Sync`, and must not have
68 a [`Drop`][drop] implementation.
74 Both `const` and `static` have requirements for giving them a value. They must
75 be given a value that’s a constant expression. In other words, you cannot use
76 the result of a function call or anything similarly complex or at runtime.
78 # Which construct should I use?
80 Almost always, if you can choose between the two, choose `const`. It’s pretty
81 rare that you actually want a memory location associated with your constant,
82 and using a `const` allows for optimizations like constant propagation not only
83 in your crate but downstream crates.