File tree 1 file changed +40
-5
lines changed
1 file changed +40
-5
lines changed 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