Boxing data
The first smart pointer we are going to look at is the Box
. This very special type is the analogue to C++'s unique_ptr
, a pointer to data stored on the heap that deletes said data automatically when it's out of scope. Because of the shift from stack to heap, Box
can allow you some flexibility by intentionally losing type information.
How to do it...
In the
bin
folder, create a file calledboxing.rs
.Add the following code and run it with
cargo run --bin boxing
:
1 use std::fs::File; 2 use std::io::BufReader; 3 use std::result::Result; 4 use std::error::Error; 5 use std::io::Read; 6 use std::fmt::Debug; 7 8 #[derive(Debug)] 9 struct Node<T> { 10 data: T, 11 child_nodes: Option<(BoxedNode<T>, BoxedNode<T>)>, 12 } 13 type BoxedNode<T> = Box<Node<T>>; 14 15 impl<T> Node<T> { 16 fn new(data: T) -> Self { 17 Node { 18 data, 19 child_nodes: None, 20 } 21 }...