简体   繁体   中英

Rust Traits - How can I use a trait without expending it?

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();
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f88125ab8848d9350a2248ae29843eba

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?

Your announce_state(self: Box<Self>) is defined to move the value. Instead define it as announce_state(&self) and then it would work.

Example: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=463e5166de4168b880173a35379cb4a2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM