taiki-e / pin-project-lite

A lightweight version of pin-project written with declarative macros.
https://docs.rs/pin-project-lite
Apache License 2.0
216 stars 15 forks source link

Is it possible to call struct method? #10

Closed iamnhphu closed 4 years ago

iamnhphu commented 4 years ago
use std::pin::Pin;
use pin_project_lite::pin_project;
pin_project! {
    struct Struct<T, U> {
        #[pin]
        pinned: T,
        unpinned: U,
    }
}

impl<T, U> Struct<T, U> {
    fn foo(self: Pin<&mut Self>) {
        let this = self.project();
        //
        this.bar();
    }

    fn bar(&self) {

    }
}

Compiler emit error:

no method named bar found for type _::Projection<'_, T, U> in the current scope method not found in _::Projection<'_, T, U>

taiki-e commented 4 years ago

.project() returns a different type from self, so it needs to call bar from self directly:

  impl<T, U> Struct<T, U> {
-     fn foo(self: Pin<&mut Self>) {
-         let this = self.project();
+     fn foo(mut self: Pin<&mut Self>) {
+         let this = self.as_mut().project();
          //
-         this.bar();
+         self.bar();
      }

(and project consumes self, so reborrow the Pin<&mut Self> via as_mut.)

iamnhphu commented 4 years ago

Thank you for your help