Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on Box in Rust

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

In [ ]:
:timing
:sccache 1

Tips and Traps

  1. Box<dyn Trait> is a syntax sugar for Box<dyn Trait + 'static>. If the trait inside Box does not have a static life time, you have to specify it manually, e.g., Box<dyn Trait + 'some_life_time>.

  2. You can leak a memory to make it has a static life time using Box::leak.

In [2]:
let b = Box::new(5);
b
Out[2]:
5
In [3]:
println!("b = {}", b);
b = 5
In [4]:
*b
Out[4]:
5

Use Box to Construct Recursive Types

In [6]:
enum List {
    Cons(i32, List),
    Nil,
}
enum List {
^^^^^^^^^ recursive type has infinite size
    Cons(i32, List),
              ^^^^ recursive without indirection
recursive type `List` has infinite size
help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `List` representable

Box<
In [3]:
#[derive(Debug)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

use List::{Cons, Nil};
In [4]:
let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
list
Out[4]:
Cons(1, Cons(2, Cons(3, Nil)))
In [10]:
match list {
    Cons(val, tail) => {
        println!("{}", val);
    },
    _ => println!("End of the list"),
}
1
Out[10]:
()
In [ ]:

Comments