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