docs: mention static methods

/cc #4217
This commit is contained in:
Tim Chevalier 2012-12-19 21:32:19 -07:00
parent 2d313fe501
commit b99a2542f3
2 changed files with 43 additions and 2 deletions

View File

@ -1195,8 +1195,23 @@ Values with a trait type can have [methods called](#method-call-expressions) on
for any method in the trait, for any method in the trait,
and can be used to instantiate type parameters that are bounded by the trait. and can be used to instantiate type parameters that are bounded by the trait.
Trait methods may be static. Trait methods may be static,
Currently, implementations of static methods behave like functions declared in the implementation's module. which means that they lack a `self` argument.
This means that they can only be called with function call syntax (`f(x)`)
and not method call syntax (`obj.f()`).
The way to refer to the name of a static method is to qualify it with the trait name,
treating the trait name like a module.
For example:
~~~~
trait Num {
static pure fn from_int(n: int) -> self;
}
impl float: Num {
static pure fn from_int(n: int) -> float { n as float }
}
let x: float = Num::from_int(42);
~~~~
Traits can have _constraints_ for example, in Traits can have _constraints_ for example, in

View File

@ -2076,6 +2076,32 @@ the preferred way to use traits polymorphically.
This usage of traits is similar to Haskell type classes. This usage of traits is similar to Haskell type classes.
## Static methods
Traits can define _static_ methods, which don't have an implicit `self` argument.
The `static` keyword distinguishes static methods from methods that have a `self`:
~~~~
trait Shape {
fn area() -> float;
static fn new_shape(area: float) -> Shape;
}
~~~~
Constructors are one application for static methods, as in `new_shape` above.
To call a static method, you have to prefix it with the trait name and a double colon:
~~~~
# trait Shape { static fn new_shape(area: float) -> self; }
# use float::consts::pi;
# use float::sqrt;
struct Circle { radius: float }
impl Circle: Shape {
static fn new_shape(area: float) -> Circle { Circle { radius: sqrt(area / pi) } }
}
let s: Circle = Shape::new_shape(42.5);
~~~~
## Trait constraints ## Trait constraints
We can write a trait declaration that is _constrained_ to only be implementable on types that We can write a trait declaration that is _constrained_ to only be implementable on types that