]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/const-and-static.md
book: Fix broken link to unsafe chapter
[rust.git] / src / doc / trpl / const-and-static.md
1 % `const` and `static`
2
3 Rust has a way of defining constants with the `const` keyword:
4
5 ```rust
6 const N: i32 = 5;
7 ```
8
9 Unlike [`let`][let] bindings, you must annotate the type of a `const`.
10
11 [let]: variable-bindings.html
12
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
17 this reason.
18
19 # `static`
20
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
24 location in memory.
25
26 Here’s an example:
27
28 ```rust
29 static N: i32 = 5;
30 ```
31
32 [const]: const.html
33
34 Unlike [`let`][let] bindings, you must annotate the type of a `static`.
35
36 [let]: variable-bindings.html
37
38 Statics live for the entire lifetime of a program, and therefore any
39 reference stored in a constant has a [`’static` lifetime][lifetimes]:
40
41 ```rust
42 static NAME: &'static str = "Steve";
43 ```
44
45 [lifetimes]: lifetimes.html
46
47 ## Mutability
48
49 You can introduce mutability with the `mut` keyword:
50
51 ```rust
52 static mut N: i32 = 5;
53 ```
54
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:
58
59 ```rust
60 # static mut N: i32 = 5;
61
62 unsafe {
63     N += 1;
64
65     println!("N: {}", N);
66 }
67 ```
68
69 [unsafe]: unsafe.html
70
71 Furthermore, any type stored in a `static` must be `Sync`.
72
73 # Initializing
74
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.
78
79 # Which construct should I use?
80
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.
85
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.