File tree 2 files changed +31
-0
lines changed
2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change @@ -1107,6 +1107,19 @@ let mut a: Animal = Dog;
1107
1107
a = Cat;
1108
1108
~~~~
1109
1109
1110
+ Enumeration constructors can have either named or unnamed fields:
1111
+ ~~~~
1112
+ enum Animal {
1113
+ Dog (~str, float),
1114
+ Cat { name: ~str, weight: float }
1115
+ }
1116
+
1117
+ let mut a: Animal = Dog(~"Cocoa", 37.2);
1118
+ a = Cat{ name: ~"Spotty", weight: 2.7 };
1119
+ ~~~~
1120
+
1121
+ In this example, ` Cat ` is a _ struct-like enum variant_ ,
1122
+ whereas ` Dog ` is simply called an enum variant.
1110
1123
### Constants
1111
1124
1112
1125
~~~~~~~~ {.ebnf .gram}
Original file line number Diff line number Diff line change @@ -733,6 +733,24 @@ fn point_from_direction(dir: Direction) -> Point {
733
733
}
734
734
~~~~
735
735
736
+ A special kind of enum variant, called _ struct-like enums_ ,
737
+ can have its fields extracted with dot notation and not just destructuring.
738
+ For example:
739
+
740
+ ~~~~
741
+ # struct Point {x: float, y: float}
742
+ # fn square(x: float) -> float { x * x }
743
+ enum Shape {
744
+ Circle { center: Point, radius: float },
745
+ Rectangle { left: Point, right: Point }
746
+ }
747
+ fn area(sh: Shape) -> float {
748
+ match sh {
749
+ Circle(c) => float::consts::pi * square(c.radius),
750
+ Rectangle(r) => r.right.x - r.left.x * r.right.y - r.right.y
751
+ }
752
+ }
753
+ ~~~~
736
754
## Tuples
737
755
738
756
Tuples in Rust behave exactly like structs, except that their fields
You can’t perform that action at this time.
0 commit comments