Expand description
§MyBox
A small, practical reimplementation of Box<T> in safe-Rust style.
This crate does one thing: it moves a value onto the heap, hands you a
pointer-sized handle, and cleans up when you’re done. Nothing fancy — just
enough to be useful in real code and to show how the standard Box<T>
works under the hood.
use my_box::MyBox;
let num = MyBox::new(42);
assert_eq!(*num, 42);
let player = MyBox::new(String::from("Ryu"));
println!("{}", *player);§Why does this exist?
Most Rust code never needs this — std::boxed::Box already does all of this
and more, with optimizations the compiler can reason about. This crate is
here because sometimes you want to see the full picture: alloc, write,
drop_in_place, dealloc, and the trait glue that makes the * operator
work the way you expect.
If you’re writing production code, use Box<T>. If you’re learning, or
you need a try_new that doesn’t panic on OOM, this might be useful.
§Examples
§Recursive type via Box
use my_box::MyBox;
#[derive(Debug, PartialEq)]
enum List<T> {
Cons(T, Box<List<T>>),
Nil,
}
let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
println!("{:?}", list);§What’s included
- Normal heap allocation —
MyBox::newandMyBox::try_new - ZST support — won’t crash on
()orPhantomData - Recursive types —
Box<List<T>>works because the indirection is a known size - Trait objects —
Box<dyn Trait>is just a fat pointer, works fine - Thread safety —
Send/Syncforwarded toT - Full access —
Deref,DerefMut,AsRef,AsMut,Borrow,BorrowMut - Standard traits —
Clone,PartialEq,PartialOrd,Ord,Hash,Debug,Display,Default,From - Raw pointer interop —
into_raw/from_rawfor when you need to cross an unsafe boundary