book icon indicating copy to clipboard operation
book copied to clipboard

Figure 4-5 misleading and/or explanation incomplete

Open profwpollock opened this issue 2 years ago • 1 comments
trafficstars

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:
    • Figure 4-5
    • scope
    • references
  • I have checked the latest main branch to see if this has already been fixed, in this file:
    • yes

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

Description of the problem: The diagram shows s referring to s1. But s1 is on the stack and not in scope in the body of calculate_length! From other languages (such as C) this would be an error.

The obvious fix is that Rust recognizes this situation at compile time and puts s1 on the heap instead. However, I suspect the figure is correct and the explanation needs a note added.

Suggested fix: Add a note:

While it appears that s1 is not in scope where s is, the lifetime of s is within the bounds of the lifetime of s1, and since s1 cannot be used until the function calculate_length returns, it is perfectly safe to use s. Rust would issue a compile time error if there was any danger, such as an attempt to save the reference s in the heap.

profwpollock avatar Dec 17 '22 04:12 profwpollock

Actually from my understanding of Rust, the box on the right is the only thing on the heap. Both s and s1 would be on the stack. And s does indeed point to s1 even though s1 is on the stack. It can do that because the borrow checker will confirm that s1 will be remain on the stack, and thus a valid address to refer to, for the entire time that s has a reference to it. So no other heap allocations are required in this instance.

c-git avatar Dec 19 '22 14:12 c-git

@c-git has the right of it! Going to close this accordingly. Thanks!

chriskrycho avatar Apr 05 '24 22:04 chriskrycho