0
fn main() {
    let s = String::from("Hello");
    drop(&s);
    println!("{}", s); // prints `Hello`
}

Playground

Why does this code compile and work? More specifically, I don't understand the following:

  1. Why I can use s in println! after I dropped it? Doesn't drop free the underlying resource making it unusable?
  2. According to the Drop trait docs, the function drop accepts a mutable reference, which doesn't make any sense to me - shouldn't it accept the value itself instead of a reference?
  3. Let's assume it accepts a mutable reference — in the code above I pass an immutable reference - so why does it still work?
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
xaxa
  • 1,057
  • 1
  • 24
  • 53
  • You are looking at 1.0.0 docs. They are valid, but they have probably been improved in the last 4 years. – Shepmaster May 27 '20 at 20:56
  • 2
    You are looking at `Drop::drop` but calling [`drop`](https://doc.rust-lang.org/std/mem/fn.drop.html). – Shepmaster May 27 '20 at 20:57
  • @Shepmaster I see, thanks - it creates a copy of a reference and then drops this copy - so basically nothing happens on `drop(&s)` line. It's not obvious that immutable references implement `Copy` by default. People say Rust is too explicit, but from what I see, sometimes it's not explicit _enough_ :) – xaxa May 27 '20 at 21:08
  • 1
    well, you write `&` pretty explicit to me – Stargateur May 27 '20 at 21:34

0 Answers0