File tree Expand file tree Collapse file tree 2 files changed +43
-2
lines changed Expand file tree Collapse file tree 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
11951195for any method in the trait,
11961196and can be used to instantiate type parameters that are bounded by the trait.
11971197
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+ ~~~~
12001215
12011216Traits can have _ constraints_ for example, in
12021217
Original file line number Diff line number Diff line change @@ -2076,6 +2076,32 @@ the preferred way to use traits polymorphically.
20762076
20772077This usage of traits is similar to Haskell type classes.
20782078
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+
20792105## Trait constraints
20802106
20812107We 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