1 % Box Syntax and Patterns
3 Currently the only stable way to create a `Box` is via the `Box::new` method.
4 Also it is not possible in stable Rust to destructure a `Box` in a match
5 pattern. The unstable `box` keyword can be used to both create and destructure
6 a `Box`. An example usage would be:
9 #![feature(box_syntax, box_patterns)]
14 Some(box n) if n < 0 => {
15 println!("Box contains negative number {}", n);
17 Some(box n) if n >= 0 => {
18 println!("Box contains non-negative number {}", n);
28 Note that these features are currently hidden behind the `box_syntax` (box
29 creation) and `box_patterns` (destructuring and pattern matching) gates
30 because the syntax may still change in the future.
34 In many languages with pointers, you'd return a pointer from a function
35 so as to avoid copying a large data structure. For example:
45 fn foo(x: Box<BigStruct>) -> Box<BigStruct> {
50 let x = Box::new(BigStruct {
60 The idea is that by passing around a box, you're only copying a pointer, rather
61 than the hundred `int`s that make up the `BigStruct`.
63 This is an antipattern in Rust. Instead, write this:
66 #![feature(box_syntax)]
75 fn foo(x: Box<BigStruct>) -> BigStruct {
80 let x = Box::new(BigStruct {
86 let y: Box<BigStruct> = box foo(x);
90 This gives you flexibility without sacrificing performance.
92 You may think that this gives us terrible performance: return a value and then
93 immediately box it up ?! Isn't this pattern the worst of both worlds? Rust is
94 smarter than that. There is no copy in this code. `main` allocates enough room
95 for the `box`, passes a pointer to that memory into `foo` as `x`, and then
96 `foo` writes the value straight into the `Box<T>`.
98 This is important enough that it bears repeating: pointers are not for
99 optimizing returning values from your code. Allow the caller to choose how they
100 want to use your output.