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