File tree Expand file tree Collapse file tree 2 files changed +41
-6
lines changed Expand file tree Collapse file tree 2 files changed +41
-6
lines changed Original file line number Diff line number Diff line change @@ -5,7 +5,7 @@ refs/heads/snap-stage3: 78a7676898d9f80ab540c6df5d4c9ce35bb50463
5
5
refs/heads/try: 519addf6277dbafccbb4159db4b710c37eaa2ec5
6
6
refs/tags/release-0.1: 1f5c5126e96c79d22cb7862f75304136e204f105
7
7
refs/heads/ndm: f3868061cd7988080c30d6d5bf352a5a5fe2460b
8
- refs/heads/try2: 777ad8b20452d94111f9c834d0f277575a564ca3
8
+ refs/heads/try2: 85ed840e234184b7975d9ee7b022c0ca2cb5d8ff
9
9
refs/heads/dist-snap: ba4081a5a8573875fed17545846f6f6902c8ba8d
10
10
refs/tags/release-0.2: c870d2dffb391e14efb05aa27898f1f6333a9596
11
11
refs/tags/release-0.3: b5f0d0f648d9a6153664837026ba1be43d3e2503
Original file line number Diff line number Diff line change @@ -1002,11 +1002,46 @@ refer to that through a pointer.
1002
1002
1003
1003
## Owned boxes
1004
1004
1005
- An owned box (` ~ ` ) is a uniquely owned allocation on the heap. An owned box
1006
- inherits the mutability and lifetime of the owner as it would if there was no
1007
- box. The purpose of an owned box is to add a layer of indirection in order to
1008
- create recursive data structures or cheaply pass around an object larger than a
1009
- pointer.
1005
+ An owned box (` ~ ` ) is a uniquely owned allocation on the heap. It inherits the
1006
+ mutability and lifetime of the owner as it would if there was no box.
1007
+
1008
+ ~~~~
1009
+ let x = 5; // immutable
1010
+ let mut y = 5; // mutable
1011
+ y += 2;
1012
+
1013
+ let x = ~5; // immutable
1014
+ let mut y = ~5; // mutable
1015
+ *y += 2; // the * operator is needed to access the contained value
1016
+ ~~~~
1017
+
1018
+ The purpose of an owned box is to add a layer of indirection in order to create
1019
+ recursive data structures or cheaply pass around an object larger than a
1020
+ pointer. Since an owned box has a unique owner, it can be used to represent any
1021
+ tree data structure.
1022
+
1023
+ The following struct won't compile, because the lack of indirection would mean
1024
+ it has an infinite size:
1025
+
1026
+ ~~~~ {.xfail-test}
1027
+ struct Foo {
1028
+ child: Option<Foo>
1029
+ }
1030
+ ~~~~
1031
+
1032
+ > *** Note:*** The ` Option ` type is an enum that represents an * optional* value.
1033
+ > It's comparable to a nullable pointer in many other languages, but stores the
1034
+ > contained value unboxed.
1035
+
1036
+ Adding indirection with an owned pointer allocates the child outside of the
1037
+ struct on the heap, which makes it a finite size and won't result in a
1038
+ compile-time error:
1039
+
1040
+ ~~~~
1041
+ struct Foo {
1042
+ child: Option<~Foo>
1043
+ }
1044
+ ~~~~
1010
1045
1011
1046
## Managed boxes
1012
1047
You can’t perform that action at this time.
0 commit comments