Skip to content

Commit bbcb26f

Browse files
committed
TRPL: const and static
1 parent 3860240 commit bbcb26f

File tree

2 files changed

+68
-2
lines changed

2 files changed

+68
-2
lines changed

src/doc/trpl/const.md

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,25 @@
11
% `const`
22

3-
Coming soon!
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, and therefore any
14+
reference stored in a constant has a [`'static` lifetime][lifetimes]:
15+
16+
```rust
17+
const NAME: &'static str = "Steve";
18+
```
19+
20+
[lifetimes]: lifetimes.html
21+
22+
More specifically, constants in Rust have no fixed address in memory. This is
23+
because they’re effectively inlined to each place that they’re used. References
24+
to the same constant are not necessarily guaranteed to refer to the same memory
25+
address for this reason.

src/doc/trpl/static.md

+45-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,47 @@
11
% `static`
22

3-
Coming soon!
3+
Rust provides a ‘global variable’ sort of facility in static items. They’re
4+
similar to [constants][const], but static items aren’t inlined upon use.
5+
6+
Here’s an example:
7+
8+
```rust
9+
static N: i32 = 5;
10+
```
11+
12+
[const]: const.html
13+
14+
Unlike [`let`][let] bindings, you must annotate the type of a `static`.
15+
16+
[let]: variable-bindings.html
17+
18+
Statics live for the entire lifetime of a program, and therefore any
19+
reference stored in a constant has a [`’static` lifetime][lifetimes]:
20+
21+
```rust
22+
static NAME: &'static str = "Steve";
23+
```
24+
25+
[lifetimes]: lifetimes.html
26+
27+
## Mutability
28+
29+
You can introduce mutability with the `mut` keyword:
30+
31+
```rust
32+
static mut N: i32 = 5;
33+
```
34+
35+
Because one thread could be updating `N` while another is reading it, causing
36+
memory unsafety. As such both accessing and mutating a `static mut` is
37+
[`unsafe`][unsafe], and so must be done in an `unsafe` block:
38+
39+
```rust
40+
# static mut N: i32 = 5;
41+
42+
unsafe {
43+
N += 1;
44+
45+
println!("N: {}", N);
46+
}
47+
```

0 commit comments

Comments
 (0)