我正试着通过阅读The Rust Programming Language Book来学习《 rust 》.我现在读的是第17章,在第Trade-offs of the State Pattern章的末尾,你们需要做以下事情:
- 需要两次调用才能将状态更改为已发布.
你得到的代码是:
pub struct Post {
state: Option<Box<dyn State>>,
content: String
}
impl Post {
pub fn new() -> Post {
Post {
state: Some(Box::new(Draft {})),
content: String::new(),
}
}
pub fn add_text(&mut self, text: &str) {
self.content.push_str(text);
}
pub fn content(&self) -> &str {
self.state.as_ref().unwrap().content(self)
}
pub fn request_review(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.request_review())
}
}
pub fn approve(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve())
}
}
}
trait State {
fn request_review(self: Box<Self>) -> Box<dyn State>;
fn approve(self: Box<Self>) -> Box<dyn State>;
fn content<'a>(&self, post: &'a Post) -> &'a str {
""
}
}
struct Draft {}
impl State for Draft {
fn request_review(self: Box<Self>) -> Box<dyn State> {
Box::new(PendingReview {})
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
}
struct PendingReview {}
impl State for PendingReview {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
Box::new(Published {})
}
}
struct Published {}
impl State for Published {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
fn content<'a>(&self, post: &'a Post) -> &'a str {
&post.content
}
}
所以我所理解的是,without breaking the trait signature,你必须实现某种逻辑到PendingReview
,才能需要两次批准才能更改为Published
状态.
我想做一些像这样的事情
struct PendingReview {
reviews: i32,
}
impl PendingReview {
fn add_review(&mut self) {
self.reviews += 1;
}
pub fn ready_to_approve(&self) -> bool {
if self.reviews == 2 {
return true;
}
add_review();
return false;
}
}
然后在PendingReview
状态的approve
函数中调用ready_to_approve
,但这不起作用,因为我需要一个我没有的可变引用,如果不打破特征签名,我就不能拥有它.此外,这种方法可能还有更多我看不到的问题,实际上我对Rust还很陌生.
我真的不知道如何处理这个问题,所以任何帮助都是感激的.