-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathbox.rs
More file actions
75 lines (66 loc) · 1.66 KB
/
box.rs
File metadata and controls
75 lines (66 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#![allow(unused)]
// Smart pointer
// Pointer with metadata and additional capabilities
// Box
// - Allows data to be stored on the heap
// - Useful for data where the size is not known at compile time
// - Trait objects
// - Recursive data structure
// Box<dyn Error> = trait object that implements the Error trait
fn f() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
// Recursive data structures
#[derive(Debug)]
enum List {
Cons(i32, Box<List>),
Nil,
}
#[derive(Debug)]
struct Tree {
val: i32,
left: Option<Box<Tree>>,
right: Option<Box<Tree>>,
}
use crate::List::{Cons, Nil};
fn main() {
// Box - allocate data to heap
let b: Box<i32> = Box::new(0);
// Dereference to get the inner value
let v = *b;
println!("box: {}", v);
// List
// 3 -> 2 -> 1 -> Nil
let mut list = Cons(3, Box::new(Cons(2, Box::new(Cons(1, Box::new(Nil))))));
// Example - print all values in list
while let Cons(i, tail) = list {
print!("{} -> ", i);
// Dereference a box
list = *tail;
}
println!("Nil");
// Tree
let tree = Tree {
val: 1,
left: Some(Box::new(Tree {
val: 2,
left: None,
right: Some(Box::new(Tree {
val: 4,
left: None,
right: None,
})),
})),
right: Some(Box::new(Tree {
val: 3,
left: None,
right: None,
})),
};
// No need to dereference Box<Tree>
// Rust automatically dereferences struct fields
println!(
"tree.left.right.val: {:?}",
tree.left.unwrap().right.unwrap().val
);
}