Skip to content

Commit 85ed840

Browse files
committed
tutorial: improve the owned boxes section
1 parent 777ad8b commit 85ed840

File tree

1 file changed

+40
-5
lines changed

1 file changed

+40
-5
lines changed

doc/tutorial.md

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1002,11 +1002,46 @@ refer to that through a pointer.
10021002

10031003
## Owned boxes
10041004

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+
~~~~
10101045

10111046
## Managed boxes
10121047

0 commit comments

Comments
 (0)