Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does self: Box<Self> mean?

Tags:

rust

I'm reading Rust Programming book. in Chapter 17 i can not understand this:

self: Box<Self>

You can easily explain?

like image 351
Alex Quchuloria Avatar asked Aug 08 '26 08:08

Alex Quchuloria


1 Answers

First, let's give a bit of a context, as described in the book:

trait State {
    fn request_review(self: Box<Self>) -> Box<dyn State>;
}

A bit further below in the book, it's explained:

We’ve added the request_review method to the State trait; all types that implement the trait will now need to implement the request_review method. Note that rather than having self, &self, or &mut self as the first parameter of the method, we have self: Box<Self>. This syntax means the method is only valid when called on a Box holding the type. This syntax takes ownership of Box<Self>, invalidating the old state so the state value of the Post can transform into a new state.

Let me give you an example. Say we have a struct A that implements State:

struct A {}

impl State for A {
    fn request_review(self: Box<Self>) -> Box<dyn State> {
        todo!();
    }
}

If we tried this code:

let a = A {};
a.request_review();

, we would get a compiler error. However, if we tried the code below, there would be no problem:

let a = A {};
Box::new(a).request_review();
like image 84
at54321 Avatar answered Aug 10 '26 03:08

at54321