]>
Commit | Line | Data |
---|---|---|
bd371182 AL |
1 | % Associated Constants |
2 | ||
3 | With the `associated_consts` feature, you can define constants like this: | |
4 | ||
d9579d0f | 5 | ```rust |
bd371182 AL |
6 | #![feature(associated_consts)] |
7 | ||
8 | trait Foo { | |
9 | const ID: i32; | |
10 | } | |
11 | ||
12 | impl Foo for i32 { | |
13 | const ID: i32 = 1; | |
14 | } | |
15 | ||
16 | fn main() { | |
17 | assert_eq!(1, i32::ID); | |
18 | } | |
19 | ``` | |
20 | ||
21 | Any implementor of `Foo` will have to define `ID`. Without the definition: | |
22 | ||
23 | ```rust,ignore | |
24 | #![feature(associated_consts)] | |
25 | ||
26 | trait Foo { | |
27 | const ID: i32; | |
28 | } | |
29 | ||
30 | impl Foo for i32 { | |
31 | } | |
32 | ``` | |
33 | ||
34 | gives | |
35 | ||
36 | ```text | |
37 | error: not all trait items implemented, missing: `ID` [E0046] | |
38 | impl Foo for i32 { | |
39 | } | |
40 | ``` | |
41 | ||
42 | A default value can be implemented as well: | |
43 | ||
d9579d0f | 44 | ```rust |
bd371182 AL |
45 | #![feature(associated_consts)] |
46 | ||
47 | trait Foo { | |
48 | const ID: i32 = 1; | |
49 | } | |
50 | ||
51 | impl Foo for i32 { | |
52 | } | |
53 | ||
54 | impl Foo for i64 { | |
55 | const ID: i32 = 5; | |
56 | } | |
57 | ||
58 | fn main() { | |
59 | assert_eq!(1, i32::ID); | |
60 | assert_eq!(5, i64::ID); | |
61 | } | |
62 | ``` | |
63 | ||
64 | As you can see, when implementing `Foo`, you can leave it unimplemented, as | |
65 | with `i32`. It will then use the default value. But, as in `i64`, we can also | |
66 | add our own definition. | |
67 | ||
68 | Associated constants don’t have to be associated with a trait. An `impl` block | |
69 | for a `struct` works fine too: | |
70 | ||
d9579d0f | 71 | ```rust |
bd371182 AL |
72 | #![feature(associated_consts)] |
73 | ||
74 | struct Foo; | |
75 | ||
76 | impl Foo { | |
77 | pub const FOO: u32 = 3; | |
78 | } | |
79 | ``` |