]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/items/constant-items.md
New upstream version 1.23.0+dfsg1
[rustc.git] / src / doc / reference / src / items / constant-items.md
1 # Constant items
2
3 A *constant item* is a named _[constant value]_ which is not associated with a
4 specific memory location in the program. Constants are essentially inlined
5 wherever they are used, meaning that they are copied directly into the relevant
6 context when used. References to the same constant are not necessarily
7 guaranteed to refer to the same memory address.
8
9 Constant values must not have destructors, and otherwise permit most forms of
10 data. Constants may refer to the address of other constants, in which case the
11 address will have elided lifetimes where applicable, otherwise – in most cases
12 – defaulting to the `static` lifetime. (See below on [static lifetime
13 elision].) The compiler is, however, still at liberty to translate the constant
14 many times, so the address referred to may not be stable.
15
16 Constants must be explicitly typed. The type may be any type that doesn't
17 implement [`Drop`] and has a `'static` lifetime: any references it contains
18 must have `'static` lifetimes.
19
20 ```rust
21 const BIT1: u32 = 1 << 0;
22 const BIT2: u32 = 1 << 1;
23
24 const BITS: [u32; 2] = [BIT1, BIT2];
25 const STRING: &'static str = "bitstring";
26
27 struct BitsNStrings<'a> {
28 mybits: [u32; 2],
29 mystring: &'a str,
30 }
31
32 const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
33 mybits: BITS,
34 mystring: STRING,
35 };
36 ```
37
38 [constant value]: expressions.html#constant-expressions
39 [static lifetime elision]: items/static-items.html#static-lifetime-elision
40 [`Drop`]: the-drop-trait.html