1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2024-12-17 23:23:43 +02:00
comprehensive-rust/src/std/box.md

40 lines
1.3 KiB
Markdown
Raw Normal View History

2022-12-21 17:36:30 +02:00
# `Box`
[`Box`][1] is an owned pointer to data on the heap:
```rust,editable
fn main() {
let five = Box::new(5);
println!("five: {}", *five);
}
```
```bob
Stack Heap
.- - - - - - -. .- - - - - - -.
: : : :
: five : : :
: +-----+ : : +-----+ :
: | o---|---+-----+-->| 5 | :
: +-----+ : : +-----+ :
: : : :
: : : :
`- - - - - - -' `- - - - - - -'
```
`Box<T>` implements `Deref<Target = T>`, which means that you can [call methods
from `T` directly on a `Box<T>`][2].
[1]: https://doc.rust-lang.org/std/boxed/struct.Box.html
[2]: https://doc.rust-lang.org/std/ops/trait.Deref.html#more-on-deref-coercion
2023-01-11 14:29:43 +02:00
<details>
2023-02-22 17:08:50 +02:00
* `Box` is like `std::unique_ptr` in C++, except that it's guaranteed to be not null.
2023-02-09 22:55:19 +02:00
* In the above example, you can even leave out the `*` in the `println!` statement thanks to `Deref`.
* A `Box` can be useful when you:
* have a type whose size that can't be known at compile time, but the Rust compiler wants to know an exact size.
* want to transfer ownership of a large amount of data. To avoid copying large amounts of data on the stack, instead store the data on the heap in a `Box` so only the pointer is moved.
2023-01-11 14:29:43 +02:00
</details>