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][const], but static items aren’t inlined upon use. This
23 means that there is only one instance for each value, and it’s at a fixed
34 Unlike [`let`][let] bindings, you must annotate the type of a `static`.
36 [let]: variable-bindings.html
38 Statics live for the entire lifetime of a program, and therefore any
39 reference stored in a constant has a [`’static` lifetime][lifetimes]:
42 static NAME: &'static str = "Steve";
45 [lifetimes]: lifetimes.html
49 You can introduce mutability with the `mut` keyword:
52 static mut N: i32 = 5;
55 Because this is mutable, one thread could be updating `N` while another is
56 reading it, causing memory unsafety. As such both accessing and mutating a
57 `static mut` is [`unsafe`][unsafe], and so must be done in an `unsafe` block:
60 # static mut N: i32 = 5;
71 Furthermore, any type stored in a `static` must be `Sync`.
75 Both `const` and `static` have requirements for giving them a value. They may
76 only be given a value that’s a constant expression. In other words, you cannot
77 use the result of a function call or anything similarly complex or at runtime.
79 # Which construct should I use?
81 Almost always, if you can choose between the two, choose `const`. It’s pretty
82 rare that you actually want a memory location associated with your constant,
83 and using a const allows for optimizations like constant propagation not only
84 in your crate but downstream crates.
86 A const can be thought of as a `#define` in C: it has metadata overhead but it
87 has no runtime overhead. “Should I use a #define or a static in C,” is largely
88 the same question as whether you should use a const or a static in Rust.