Rust Box vs pointer

Viewed 205

Reading the Rust documentation about Box it seems to work just like a normal pointer.
One example they give is this:

enum List {
    Cons(i32, Box<List>),
    Nil,
}

use crate::List::{Cons, Nil};

fn main() {
    let list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil))))));
}

But one could also write this:

#[derive(Debug)]
enum List<'a> {
    Cons(i32, &'a List<'a>),
    Nil,
}

use crate::List::{Cons, Nil};

fn main() {
    let list = Cons(1, &Cons(2, &Cons(3, &Nil)));

    println!("{:?}", list);
}

What are the compelling reasons to use Box?
Is it just for syntactic sugar?
Are there situations that we could/should only use Box instead of a pointer?
If Box works like a pointer should I prefer to use a Box instead of a pointer?
Why don't I need lifetimes when using a Box?

1 Answers

What are the compelling reasons to use Box?

Box allows to move a value to be heap allocated. Otherwise, by default, it would be stack allocated.

Literally from the documentation description:

A pointer type for heap allocation.

Is it just for syntactic sugar?

Not it is not, you can use raw pointers, but Box are subdue to rust borrowing rules.

Are there situations that we could/should only use Box instead of a pointer?

If you want to use safe rust code, you will be using Box most of the time.

If Box works like a pointer should I prefer to use a Box instead of a pointer?

As before, unless something specific is needed you will be using Box.

Why don't I need lifetimes when using a Box?

You don't need if the object is owned, if it is a & reference for example you will need to add a lifetime annotation sometimes. For example, if you somehow need a heap allocated reference to a dynamic trait:

struct MyStruct<'a> {
    data: Box<&'a dyn SomeTrait>
}
Related