rust-lang / book

The Rust Programming Language

Home Page:https://doc.rust-lang.org/book/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Suggestion: Elaborate on Using Box<T> to Point to Data on the Heap

GunnarBernsteinHH opened this issue · comments

URL to the section(s) of the book with this problem:

Description of the problem:

The 'Box' is a unique feature I have not seen in any language. While understanding that a value is created on the heap and referenced I felt underinformed about the acutal usages, as all example only use the println! macro. So, a simple task like comparing a boxed value cannot be deducted from the documentation easily.

I was searching quite a bit on how to change a box value and was expecting something like

let mut x = Box::new(10);
wrong: x.value = 11;
wrong: x.set(11);

Suggested fix:
So I believe, some examples could clarify this, e.g.

let a = Box::new(10);
let b = *a;
if (*a == 10) {
    println!("Box a is still 10!");
}

let mut c = Box::new(20);
change_box_value(&mut c, 42);

fn change_box_value(bx: &mut Box<i32>, value: i32) {
    **bx = value;
}

Thanks for writing this up! However, note that the very next major section after introducing and using Box shows exactly this! On the one hand, I can see how it might be nice to get there sooner. On the other hand, that explanation pulls in several more concepts that are important for understanding how dereferencing works. I think this is a case where an author just has to pick an order to introduce things, and none will be perfect—and readers should keep reading to see if their question gets answered! Often, it will, as it does here!