book
book copied to clipboard
ch17-03-oo-design-patterns ― use _interior mutability_ for sample
- [✔] I have checked the latest
mainbranch 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
statetoNonetemporarily rather than setting it directly with code likeself.state = self.state.request_review();to get ownership of thestatevalue. This ensuresPostcan’t use the oldstatevalue 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.