In the Rust book (Chapter 17) it shows some example of traits. In one set of examples, they explain using states by having a dyn trait in a struct. But, in examples of use, they always reset the trait. I am attempting to use a trait without expending it, and it's proving to be difficult:
struct Post {
post_state: Option<Box<dyn PostState>>,
}
trait PostState {
fn announce_state(self: Box<Self>);
}
impl Post {
pub fn new() -> Post {
Post {
post_state: Some(Box::new(Draft{})),
}
}
pub fn announce_state(&self) {
if let Some(s) = self.post_state.as_ref() {
s.announce_state();
}
}
}
struct Draft{}
impl PostState for Draft {
fn announce_state(self: Box<Self>) {
println!("Draft");
}
}
fn main() {
let mut my_post = Post::new();
my_post.announce_state();
}
I have attempted various methods of calling the traits announce_state function, all with failure. In the book, they use something like:
if let Some(s) = self.post_state.take() {
self.post_state = Some(s.approve_post())
}
But, doing this starts by setting the 'state' to None before reimplementing. I would like to be able to call a function of a trait without first consuming it. How would this be done?