From f9bb7b7768a00a31434952b05ad44202ffad2a11 Mon Sep 17 00:00:00 2001 From: Luca Bruno Date: Wed, 20 Mar 2013 00:15:57 +0100 Subject: [PATCH] Tutorial: make struct section more coherent In struct section of tutorial, make everything more coherent and clear by always using "struct Point". Also, do not prematurely introduce pointers and arrays. Fixes #5240 Signed-off-by: Luca Bruno --- doc/tutorial.md | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/doc/tutorial.md b/doc/tutorial.md index 699fc33863a1c..71d31407d24f5 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -579,21 +579,30 @@ Structs are quite similar to C structs and are even laid out the same way in memory (so you can read from a Rust struct in C, and vice-versa). Use the dot operator to access struct fields, as in `mypoint.x`. -Inherited mutability means that any field of a struct may be mutable, if the -struct is in a mutable slot (or a field of a struct in a mutable slot, and -so forth). - ~~~~ -struct Stack { - content: ~[int], - head: uint +struct Point { + x: float, + y: float } ~~~~ -With a value (say, `mystack`) of such a type in a mutable location, you can do -`mystack.head += 1`. But in an immutable location, such an assignment to a +Inherited mutability means that any field of a struct may be mutable, if the +struct is in a mutable slot (or a field of a struct in a mutable slot, and +so forth). + +With a value (say, `mypoint`) of such a type in a mutable location, you can do +`mypoint.y += 1.0`. But in an immutable location, such an assignment to a struct without inherited mutability would result in a type error. +~~~~ {.xfail-test} +# struct Point { x: float, y: float } +let mut mypoint = Point { x: 1.0, y: 1.0 }; +let origin = Point { x: 0.0, y: 0.0 }; + +mypoint.y += 1.0; // mypoint is mutable, and its fields as well +origin.y += 1.0; // ERROR: assigning to immutable field +~~~~ + `match` patterns destructure structs. The basic syntax is `Name { fieldname: pattern, ... }`: