Skip to content

Commit efc319f

Browse files
committed
c17: add doc for as_ref() and take()
1 parent e2b4afe commit efc319f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

c17_state_pattern/src/lib.rs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,14 @@ impl Post {
1212
}
1313

1414
pub fn content(&self) -> &str {
15+
/*
16+
We call the *as_ref()* method on the Option because we want a reference to
17+
the value inside the Option rather than ownership of the value. Because
18+
state is an Option<Box<dyn State>> , when we call as_ref() , an
19+
Option<&Box<dyn State>> is returned. If we didn’t call as_ref , we would
20+
get an error because we can’t move state out of the borrowed &self of
21+
the function parameter
22+
*/
1523
self.state.as_ref().unwrap().content(self)
1624
}
1725

@@ -20,6 +28,21 @@ impl Post {
2028
}
2129

2230
pub fn request_review(&mut self) {
31+
/*
32+
To consume the old state, the request_review method needs to take ownership
33+
of the state value. This is where the Option in the state field of Post
34+
comes in: we call the *take()* method to take the Some value out of the state
35+
field and leave a None in its place, because Rust doesn’t let us have
36+
unpopulated fields in structs. This lets us move the state value out of
37+
Post rather than borrowing it. Then we’ll set the post’s state value to
38+
the result of this operation.
39+
40+
We need to set state to None temporarily rather than setting it directly
41+
with code like self.state = self.state.request_review(); to get ownership
42+
of the state value. This ensures Post can’t use the old state value after
43+
we’ve transformed it into a new state.
44+
45+
*/
2346
//self.state = Some(self.state.take().expect("Valid state").request_review());
2447
if let Some(s) = self.state.take() {
2548
self.state = Some(s.request_review())

0 commit comments

Comments
 (0)