book icon indicating copy to clipboard operation
book copied to clipboard

ch17-03-oo-design-patterns ― use _interior mutability_ for sample

Open deep-outcome opened this issue 3 years ago • 0 comments
trafficstars

  • [✔] I have checked the latest main branch to see if this has already been fixed
  • [✔] I have searched existing issues and pull requests for duplicates

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

https://doc.rust-lang.org/book/ch17-03-oo-design-patterns.html#requesting-a-review-of-the-post-changes-its-state

Description of the problem:

Exactly this paragraph loses sense little.

We need to set state to None temporarily rather than setting it directly with code like self.state = self.state.request_review(); to get ownership of the state value. This ensures Post can’t use the old state value after we’ve transformed it into a new state.

This since ownership is not needed to be taken. As per sample bellow explains

struct Dropper {
    val: u32,
}

struct Test {
    val: Box<Dropper>,
}

impl Drop for Dropper {
    fn drop(&mut self) {
        println!("  -- drop {}", self.val);
    }
}
fn main() {
    let mut test = Test {
        val: Box::new(Dropper { val: 3 }),
    };

    {
        test.val = Box::new(Dropper { val: 4 });
        println!("  -- val {}", test.val.val);
    }

    println!("  -- back in outter scope");
}
  -- drop 3
  -- val 4
  -- back in outter scope
  -- drop 4

obviously while ownership was not explicitly taken ― test.val = 
…, old value goes immediately of scope and thus is dropped. This implies no option for usage of old state value after transformation into a new state.

Suggested fix:

Go with RefCell or Cell in either way including raw pointers. Semantically anywhere None is possible/expected thus more impressive design goes with interior mutability. There come small wart for reading content anyhow instead, still making unsense less obvious.

deep-outcome avatar Oct 03 '22 22:10 deep-outcome