Skip to content

Commit 964fc86

Browse files
author
Diggory Hardy
committed
Tutorial: comment on how mutability applies to boxes
1 parent cb91e91 commit 964fc86

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

doc/tutorial.md

+30
Original file line numberDiff line numberDiff line change
@@ -1067,6 +1067,26 @@ let mut d = @mut 5; // mutable variable, mutable box
10671067
d = @mut 15;
10681068
~~~~
10691069

1070+
A mutable variable and an immutable variable can refer to the same box, given
1071+
that their types are compatible. Mutability of a box is a property of its type,
1072+
however, so for example a mutable hande to an immutable box cannot be assigned
1073+
a reference to a mutable box.
1074+
1075+
~~~~
1076+
let a = @1; // immutable box
1077+
let b = @mut 2; // mutable box
1078+
1079+
let mut c : @int; // declare a variable with type managed immutable int
1080+
let mut d : @mut int; // and one of type managed mutable int
1081+
1082+
c = a; // box type is the same
1083+
d = b; // box type is the same
1084+
1085+
// but b cannot be assigned to c, or a to d
1086+
c = b; // error
1087+
~~~~
1088+
1089+
10701090
# Move semantics
10711091

10721092
Rust uses a shallow copy for parameter passing, assignment and returning values
@@ -1081,6 +1101,16 @@ let y = x.clone(); // y is a newly allocated box
10811101
let z = x; // no new memory allocated, x can no longer be used
10821102
~~~~
10831103

1104+
Since in owned boxes mutabilility is a property of the owner, not the
1105+
box, mutable boxes may become immutable when they are moved, and vice-versa.
1106+
1107+
~~~~
1108+
let r = ~13;
1109+
let mut s = r; // box becomes mutable
1110+
*s += 1;
1111+
let t = s; // box becomes immutable
1112+
~~~~
1113+
10841114
# Borrowed pointers
10851115

10861116
Rust's borrowed pointers are a general purpose reference type. In contrast with

0 commit comments

Comments
 (0)