someguynamedjosh / ouroboros

Easy self-referential struct generation for Rust.
Apache License 2.0
524 stars 33 forks source link

can't impl Drop on self referencing structs #75

Open doy-materialize opened 1 year ago

doy-materialize commented 1 year ago
#[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 commented 1 year ago

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