Avoiding heap allocated box pointers

Rust allocates space in the stack by default, since it's much faster than using the heap. Nevertheless, sometimes, when we do not know the size of objects at compile time, we need to use the heap to allocate new structures. Rust makes this explicit by using the Vec, String, and Box types, for example. The last one allows us to put in the heap any kind of object, which is usually a bad idea, but sometimes it's a must.

Check out, for example, the following code:

fn main() {    let mut int = Box::new(5);    *int += 5;    println!("int: {}", int);}

This code compiles perfectly, and it tells us that the integer is 10 (5 + 5). The main issue with this is that it does a heap allocation, doing a system call that needs ...

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.