Skip to content

Commit 77ce30f

Browse files
committed
Auto merge of #24990 - steveklabnik:doc_associated_constants, r=alexcrichton
2 parents 796be61 + 6b465f5 commit 77ce30f

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

src/doc/trpl/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,5 +64,6 @@
6464
* [Benchmark Tests](benchmark-tests.md)
6565
* [Box Syntax and Patterns](box-syntax-and-patterns.md)
6666
* [Slice Patterns](slice-patterns.md)
67+
* [Associated Constants](associated-constants.md)
6768
* [Glossary](glossary.md)
6869
* [Academic Research](academic-research.md)

src/doc/trpl/associated-constants.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
% Associated Constants
2+
3+
With the `associated_consts` feature, you can define constants like this:
4+
5+
```rust
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+
44+
```rust
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+
71+
```rust
72+
#![feature(associated_consts)]
73+
74+
struct Foo;
75+
76+
impl Foo {
77+
pub const FOO: u32 = 3;
78+
}
79+
```

0 commit comments

Comments
 (0)