Ch::15::Box:: I find this example-selection a bit confusing

โš“ rust    ๐Ÿ“… 2025-07-03    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 3      

surdeus

Here the point of the article and the write up is very good, and very clear.

But there is an important caveat imho, in this paragraph:

The reason the deref method returns a reference to a value, and that the plain dereference outside the parentheses in *(y.deref()) is still necessary, has to do with the ownership system. If the deref method returned the value directly instead of a reference to the value, the value would be moved out of self . We donโ€™t want to take ownership of the inner value inside MyBox<T> in this case or in most cases where we use the dereference operator.

However, Box seems one of the only cases that this actually happens!

fn main() {
   let a = Box::<String>::new(String::from("hell"));
   let b = *a; // expects &str
   let c = *a; // but clearly wasn't
}

Playground

6 posts - 3 participants

Read full topic

๐Ÿท๏ธ rust_feed