File tree 1 file changed +74
-1
lines changed
1 file changed +74
-1
lines changed Original file line number Diff line number Diff line change @@ -866,7 +866,7 @@ implement. This interface consists of associated items, which come in
866
866
three varieties:
867
867
868
868
- functions
869
- - constants
869
+ - [ constants] ( #associated-constants )
870
870
- types
871
871
872
872
Associated functions whose first parameter is named ` self ` are called
@@ -1080,6 +1080,79 @@ let mycircle = Box::new(mycircle) as Box<Circle>;
1080
1080
let nonsense = mycircle.radius() * mycircle.area();
1081
1081
```
1082
1082
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
+
1083
1156
### Implementations
1084
1157
1085
1158
An _ implementation_ is an item that implements a [ trait] ( #traits ) for a
You can’t perform that action at this time.
0 commit comments