book icon indicating copy to clipboard operation
book copied to clipboard

Mention that the left-hand side of an assignment is dropped

Open MariusDoe opened this issue 1 year ago • 0 comments
trafficstars

  • I have searched open and closed issues and pull requests for duplicates, using these search terms:
    • drop
    • dropped
    • assign
    • assigned
    • assignment
  • I have checked the latest main branch to see if this has already been fixed, in these files:
    • https://github.com/rust-lang/book/blob/04bc1396bb857f35b5dda1d773c9571e1f253304/src/ch04-01-what-is-ownership.md
    • https://github.com/rust-lang/book/blob/04bc1396bb857f35b5dda1d773c9571e1f253304/src/ch15-03-drop.md

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

Description of the problem:

  • The book explains that a value is dropped, when its owner goes out of scope (in the Ownership Rules section of chapter 4.1), but it does not explain that they are also dropped when its owner gets assigned a different value. These are the currently listed rules: https://github.com/rust-lang/book/blob/04bc1396bb857f35b5dda1d773c9571e1f253304/src/ch04-01-what-is-ownership.md?plain=1#L86-L93
  • Chapter 15.3 explains the Drop trait (and shows the reverse drop order of multiple let bindings with some example code), but also does not mention the effect of an assignment.
  • To find out about this behavior or to find out when (if at all) values that are overwritten via assignment are dropped, one currently has to look into the reference chapter for destructors (version at issue creation), it states:

    Assignment also runs the destructor of its left-hand operand, if it's initialized.

Suggested fix:

  • In chapter 4.1, mention that a reassignment of the owner of a value also drops that value. For example, the last bullet point of the Ownership Rules may be replaced with (added parts marked):

    • When the owner goes out of scope or is assigned a different value, the (original) value will be dropped.

    Or another rule may be added:

    • When the owner is assigned a different value, the original value will be dropped.
  • In chapter 4.1, add an explaining example of the behavior, for example between these two paragraphs. The example might look like this:

    {
        let mut s = String::from("hello");
        // do stuff with s
        s = String::from("world"); // s gets reassigned, so the "hello" String is dropped here
        // do stuff with s
    }   // this scope is now over, and the "world" String will be dropped
    
  • In chapter 15.3, add an example that shows the drop behavior of an assignment, by using the CustomSmartPointer already defined in the chapter. Alternatively, extend the first example in the chapter with the assignment behavior (might be too much in a single example?).

MariusDoe avatar Aug 02 '24 18:08 MariusDoe