Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
:timing
:sccache 1Tips and Traps¶
Box<dyn Trait>is a syntax sugar forBox<dyn Trait + 'static>. If the trait insideBoxdoes not have a static life time, you have to specify it manually, e.g.,Box<dyn Trait + 'some_life_time>.You can leak a memory to make it has a static life time using Box::leak.
let b = Box::new(5);
b5println!("b = {}", b);b = 5
*b5Use 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))))));
listCons(1, Cons(2, Cons(3, Nil)))match list {
Cons(val, tail) => {
println!("{}", val);
},
_ => println!("End of the list"),
}1
()