Skip to content

Commit 3cc0fbc

Browse files
committed
doc: mention struct-like enum variants /cc #4217
1 parent 499a587 commit 3cc0fbc

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

doc/rust.md

+13
Original file line numberDiff line numberDiff line change
@@ -1107,6 +1107,19 @@ let mut a: Animal = Dog;
11071107
a = Cat;
11081108
~~~~
11091109

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.
11101123
### Constants
11111124

11121125
~~~~~~~~ {.ebnf .gram}

doc/tutorial.md

+18
Original file line numberDiff line numberDiff line change
@@ -733,6 +733,24 @@ fn point_from_direction(dir: Direction) -> Point {
733733
}
734734
~~~~
735735

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+
~~~~
736754
## Tuples
737755

738756
Tuples in Rust behave exactly like structs, except that their fields

0 commit comments

Comments
 (0)