I'm reading Rust Programming book. in Chapter 17 i can not understand this:
self: Box<Self>
You can easily explain?
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_reviewmethod to theStatetrait; all types that implement the trait will now need to implement therequest_reviewmethod. Note that rather than havingself,&self, or&mut selfas the first parameter of the method, we haveself: Box<Self>. This syntax means the method is only valid when called on aBoxholding the type. This syntax takes ownership ofBox<Self>, invalidating the old state so the state value of thePostcan 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With