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:
- https://doc.rust-lang.org/book/ch15-01-box.html
- https://doc.rust-lang.org/rust-by-example/std/box.html
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!