0

I'm learning Rust by writing a simple database, I called drop(self) in a method multiple times. While I thought the compiler would refuse to compile the code below, it compiles without warnings, but the drop(self) seems to have no effect.

Run the code on Rust Playground

fn main() {
    let database = Database::new().unwrap();
    println!("-- start of drops --");
    database.flush();
    database.flush();
    println!("-- end of main --");
}

struct Database {
}

impl Database {
    fn new () -> Result<Database, std::io::Error> {
        Ok(Database {
        })
    }

    fn flush(&self) {
        println!("in flush()");
        drop(self);
        drop(self);
    }
}

impl Drop for Database {
    fn drop(&mut self) {
        println!("call Database drop");
        let _ = self.flush();
    }
}

The actual output was

-- start of drops --
in flush()
in flush()
-- end of main --
call Database drop
in flush()

What I expected (if the code compiles) was

-- start of drops --
in flush()
call Database drop
in flush()
call Database drop
...... (repeat thousands of times)

My question is: is the Rust compiler ignores the drop(self) in the implementation of methods?

Thanks.

YuWea
  • 165
  • 9
  • 2
    I think it's this: https://stackoverflow.com/questions/55314407/what-happens-when-i-call-stdmemdrop-with-a-reference-instead-of-an-owned-val That double `drop(self)` can't be resolved to your implementation of Drop, because `self` is a shared reference. So instead this reference is dropped, not affecting the referenced object. – Sergio Tulentsev Dec 20 '21 at 13:46
  • @YuWea no you implement `Drop` for `Database` but `Drop::drop` takes a mutable reference to what it's dropping. Also what would droppoing a *shared reference* entail exactly? What `flush` does is create a copy of the `self` *shared reference* and pass that to `drop`. – Masklinn Dec 20 '21 at 14:40
  • Not to mention your code would blow up since `flush` calls `drop` and `drop` calls `flush`. – Masklinn Dec 20 '21 at 14:40
  • @Masklinn The code actually compiles and exits without panic, that bothered me. – YuWea Dec 20 '21 at 23:48

0 Answers0