Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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

: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.

let b = Box::new(5);
b
5
println!("b = {}", b);
b = 5
*b
5

Use Box to Construct Recursive Types

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<
#[derive(Debug)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

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