doc: mention struct-like enum variants /cc #4217

This commit is contained in:
Tim Chevalier 2012-12-20 00:05:21 -07:00
parent 499a58708f
commit 3cc0fbca5d
2 changed files with 31 additions and 0 deletions

View File

@ -1107,6 +1107,19 @@ let mut a: Animal = Dog;
a = Cat;
~~~~
Enumeration constructors can have either named or unnamed fields:
~~~~
enum Animal {
Dog (~str, float),
Cat { name: ~str, weight: float }
}
let mut a: Animal = Dog(~"Cocoa", 37.2);
a = Cat{ name: ~"Spotty", weight: 2.7 };
~~~~
In this example, `Cat` is a _struct-like enum variant_,
whereas `Dog` is simply called an enum variant.
### Constants
~~~~~~~~ {.ebnf .gram}

View File

@ -733,6 +733,24 @@ fn point_from_direction(dir: Direction) -> Point {
}
~~~~
A special kind of enum variant, called _struct-like enums_,
can have its fields extracted with dot notation and not just destructuring.
For example:
~~~~
# struct Point {x: float, y: float}
# fn square(x: float) -> float { x * x }
enum Shape {
Circle { center: Point, radius: float },
Rectangle { left: Point, right: Point }
}
fn area(sh: Shape) -> float {
match sh {
Circle(c) => float::consts::pi * square(c.radius),
Rectangle(r) => r.right.x - r.left.x * r.right.y - r.right.y
}
}
~~~~
## Tuples
Tuples in Rust behave exactly like structs, except that their fields