File tree 2 files changed +43
-2
lines changed
2 files changed +43
-2
lines changed Original file line number Diff line number Diff line change @@ -1195,8 +1195,23 @@ Values with a trait type can have [methods called](#method-call-expressions) on
1195
1195
for any method in the trait,
1196
1196
and can be used to instantiate type parameters that are bounded by the trait.
1197
1197
1198
- Trait methods may be static.
1199
- Currently, implementations of static methods behave like functions declared in the implementation's module.
1198
+ Trait methods may be static,
1199
+ which means that they lack a ` self ` argument.
1200
+ This means that they can only be called with function call syntax (` f(x) ` )
1201
+ and not method call syntax (` obj.f() ` ).
1202
+ The way to refer to the name of a static method is to qualify it with the trait name,
1203
+ treating the trait name like a module.
1204
+ For example:
1205
+
1206
+ ~~~~
1207
+ trait Num {
1208
+ static pure fn from_int(n: int) -> self;
1209
+ }
1210
+ impl float: Num {
1211
+ static pure fn from_int(n: int) -> float { n as float }
1212
+ }
1213
+ let x: float = Num::from_int(42);
1214
+ ~~~~
1200
1215
1201
1216
Traits can have _ constraints_ for example, in
1202
1217
Original file line number Diff line number Diff line change @@ -2076,6 +2076,32 @@ the preferred way to use traits polymorphically.
2076
2076
2077
2077
This usage of traits is similar to Haskell type classes.
2078
2078
2079
+ ## Static methods
2080
+
2081
+ Traits can define _ static_ methods, which don't have an implicit ` self ` argument.
2082
+ The ` static ` keyword distinguishes static methods from methods that have a ` self ` :
2083
+
2084
+ ~~~~
2085
+ trait Shape {
2086
+ fn area() -> float;
2087
+ static fn new_shape(area: float) -> Shape;
2088
+ }
2089
+ ~~~~
2090
+
2091
+ Constructors are one application for static methods, as in ` new_shape ` above.
2092
+ To call a static method, you have to prefix it with the trait name and a double colon:
2093
+
2094
+ ~~~~
2095
+ # trait Shape { static fn new_shape(area: float) -> self; }
2096
+ # use float::consts::pi;
2097
+ # use float::sqrt;
2098
+ struct Circle { radius: float }
2099
+ impl Circle: Shape {
2100
+ static fn new_shape(area: float) -> Circle { Circle { radius: sqrt(area / pi) } }
2101
+ }
2102
+ let s: Circle = Shape::new_shape(42.5);
2103
+ ~~~~
2104
+
2079
2105
## Trait constraints
2080
2106
2081
2107
We can write a trait declaration that is _ constrained_ to only be implementable on types that
You can’t perform that action at this time.
0 commit comments