From 3cc0fbca5d0a37f9b770db27e3ea39a00616ca4f Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Thu, 20 Dec 2012 00:05:21 -0700 Subject: [PATCH] doc: mention struct-like enum variants /cc #4217 --- doc/rust.md | 13 +++++++++++++ doc/tutorial.md | 18 ++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/doc/rust.md b/doc/rust.md index 210e07d198a..bed231de294 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -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} diff --git a/doc/tutorial.md b/doc/tutorial.md index d20ce43c3d2..b746072a53d 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -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