Skip to content

Commit 1abfbaa

Browse files
authored
Merge pull request #75 from seanmonstar/patch-1
add associated constants to items reference
2 parents 34cc3c6 + aabe117 commit 1abfbaa

File tree

1 file changed

+74
-1
lines changed

1 file changed

+74
-1
lines changed

src/items.md

+74-1
Original file line numberDiff line numberDiff line change
@@ -866,7 +866,7 @@ implement. This interface consists of associated items, which come in
866866
three varieties:
867867

868868
- functions
869-
- constants
869+
- [constants](#associated-constants)
870870
- types
871871

872872
Associated functions whose first parameter is named `self` are called
@@ -1080,6 +1080,79 @@ let mycircle = Box::new(mycircle) as Box<Circle>;
10801080
let nonsense = mycircle.radius() * mycircle.area();
10811081
```
10821082

1083+
#### Associated Constants
1084+
1085+
1086+
A trait can define constants like this:
1087+
1088+
```rust
1089+
trait Foo {
1090+
const ID: i32;
1091+
}
1092+
1093+
impl Foo for i32 {
1094+
const ID: i32 = 1;
1095+
}
1096+
1097+
fn main() {
1098+
assert_eq!(1, i32::ID);
1099+
}
1100+
```
1101+
1102+
Any implementor of `Foo` will have to define `ID`. Without the definition:
1103+
1104+
```rust,ignore
1105+
trait Foo {
1106+
const ID: i32;
1107+
}
1108+
1109+
impl Foo for i32 {
1110+
}
1111+
```
1112+
1113+
gives
1114+
1115+
```text
1116+
error: not all trait items implemented, missing: `ID` [E0046]
1117+
impl Foo for i32 {
1118+
}
1119+
```
1120+
1121+
A default value can be implemented as well:
1122+
1123+
```rust
1124+
trait Foo {
1125+
const ID: i32 = 1;
1126+
}
1127+
1128+
impl Foo for i32 {
1129+
}
1130+
1131+
impl Foo for i64 {
1132+
const ID: i32 = 5;
1133+
}
1134+
1135+
fn main() {
1136+
assert_eq!(1, i32::ID);
1137+
assert_eq!(5, i64::ID);
1138+
}
1139+
```
1140+
1141+
As you can see, when implementing `Foo`, you can leave it unimplemented, as
1142+
with `i32`. It will then use the default value. But, as in `i64`, we can also
1143+
add our own definition.
1144+
1145+
Associated constants don’t have to be associated with a trait. An `impl` block
1146+
for a `struct` or an `enum` works fine too:
1147+
1148+
```rust
1149+
struct Foo;
1150+
1151+
impl Foo {
1152+
const FOO: u32 = 3;
1153+
}
1154+
```
1155+
10831156
### Implementations
10841157

10851158
An _implementation_ is an item that implements a [trait](#traits) for a

0 commit comments

Comments
 (0)