summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTim Chevalier <chevalier@alum.wellesley.edu>2012-12-19 21:32:19 -0700
committerTim Chevalier <chevalier@alum.wellesley.edu>2012-12-19 21:32:19 -0700
commitb99a2542f38a2d08b863d2e2ab73bfd64647e520 (patch)
tree0f5fe18d751fcd5482d639aea0175aa70a858404
parent2d313fe5011acfa28b8771c5975be37e1c84fd73 (diff)
docs: mention static methods
/cc #4217
-rw-r--r--doc/rust.md19
-rw-r--r--doc/tutorial.md26
2 files changed, 43 insertions, 2 deletions
diff --git a/doc/rust.md b/doc/rust.md
index 8bff1aa37af..f1064c395aa 100644
--- a/doc/rust.md
+++ b/doc/rust.md
@@ -1195,8 +1195,23 @@ Values with a trait type can have [methods called](#method-call-expressions) on
for any method in the trait,
and can be used to instantiate type parameters that are bounded by the trait.
-Trait methods may be static.
-Currently, implementations of static methods behave like functions declared in the implementation's module.
+Trait methods may be static,
+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
diff --git a/doc/tutorial.md b/doc/tutorial.md
index c7b75993f11..8c57f2883ad 100644
--- a/doc/tutorial.md
+++ b/doc/tutorial.md
@@ -2076,6 +2076,32 @@ the preferred way to use traits polymorphically.
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
We can write a trait declaration that is _constrained_ to only be implementable on types that