Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

can't impl Drop on self referencing structs #75

Open
doy-materialize opened this issue Nov 18, 2022 · 1 comment
Open

can't impl Drop on self referencing structs #75

doy-materialize opened this issue Nov 18, 2022 · 1 comment

Comments

@doy-materialize
Copy link

#[ouroboros::self_referencing]
struct Foo {
    a: String,
    #[borrows(a)]
    b: &'this str,
}

impl Drop for Foo {
    fn drop(&mut self) {}
}

results in this error:

error[E0509]: cannot move out of type `Foo`, which implements the `Drop` trait
 --> src/main.rs:1:1
  |
1 | #[ouroboros::self_referencing]
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  | |
  | cannot move out of here
  | move occurs because `self.a` has type `AliasableBox<String>`, which does not implement the `Copy` trait
  | help: consider borrowing here: `&#[ouroboros::self_referencing]`
  |
  = note: this error originates in the attribute macro `ouroboros::self_referencing` (in Nightly builds, run with -Z macro-backtrace for more info)
@Qqwy
Copy link

Qqwy commented Feb 12, 2023

I am not sure Ouroboros could/should provide a nice API for this.

As per the Destructors page in the Rustonomicon:
(Emphasis added by me)

Note that taking &mut self means that even if you could suppress recursive Drop, Rust will prevent you from e.g. moving fields out of self. For most types, this is totally fine.

For self-referencing types, it is not fine. This is the error you are encountering above.


But there is a simple workaround: Wrap the self-referencing struct in a 'normal' struct, and use the normal borrow_fieldname(), with_fieldname_mut() etc. functions in there as desired:

pub struct Foo(FooInner);

#[ouroboros::self_referencing]
struct FooInner {
    a: String,
    #[borrows(a)]
    b: &'this str,
}

impl Drop for Foo {
    fn drop(&mut self) {
        println!("Drop called with b: {:?}", self.0.borrow_b());
        // etc
    }
}

impl Foo {
    // Use whatever parameters are appropriate to construct the default FooInner here:
    pub fn new(...) -> Foo {
      let inner = FooInnerBuilder{...}.build();
      Foo(inner)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants