]> git.lizzy.rs Git - rust.git/blob - src/doc/unstable-book/src/language-features/associated-consts.md
Auto merge of #43078 - kennytm:fix-42755-vis-can-be-empty, r=petrochenkov
[rust.git] / src / doc / unstable-book / src / language-features / associated-consts.md
1 # `associated_consts`
2
3 The tracking issue for this feature is: [#29646]
4
5 [#29646]: https://github.com/rust-lang/rust/issues/29646
6
7 ------------------------
8
9 With the `associated_consts` feature, you can define constants like this:
10
11 ```rust
12 #![feature(associated_consts)]
13
14 trait Foo {
15     const ID: i32;
16 }
17
18 impl Foo for i32 {
19     const ID: i32 = 1;
20 }
21
22 fn main() {
23     assert_eq!(1, i32::ID);
24 }
25 ```
26
27 Any implementor of `Foo` will have to define `ID`. Without the definition:
28
29 ```rust,ignore
30 #![feature(associated_consts)]
31
32 trait Foo {
33     const ID: i32;
34 }
35
36 impl Foo for i32 {
37 }
38 ```
39
40 gives
41
42 ```text
43 error: not all trait items implemented, missing: `ID` [E0046]
44      impl Foo for i32 {
45      }
46 ```
47
48 A default value can be implemented as well:
49
50 ```rust
51 #![feature(associated_consts)]
52
53 trait Foo {
54     const ID: i32 = 1;
55 }
56
57 impl Foo for i32 {
58 }
59
60 impl Foo for i64 {
61     const ID: i32 = 5;
62 }
63
64 fn main() {
65     assert_eq!(1, i32::ID);
66     assert_eq!(5, i64::ID);
67 }
68 ```
69
70 As you can see, when implementing `Foo`, you can leave it unimplemented, as
71 with `i32`. It will then use the default value. But, as in `i64`, we can also
72 add our own definition.
73
74 Associated constants don’t have to be associated with a trait. An `impl` block
75 for a `struct` or an `enum` works fine too:
76
77 ```rust
78 #![feature(associated_consts)]
79
80 struct Foo;
81
82 impl Foo {
83     const FOO: u32 = 3;
84 }
85 ```