3 ms·
> Even things that are Copy are implicitly Drop, it's just that the copy is dropped instead of the value. While that mental model could make sense in an abstra
by steveklabnik 4y ago
> Even things that are Copy are implicitly Drop, it's just that the copy is dropped instead of the value.
While that mental model could make sense in an abstract way, it's not literally true. Copy types are forbidden to implement Drop.
fn takes_drop<T: Drop>(t: T) {
todo!()
}
fn main() {
takes_drop(5i32);
}
gives
error[E0277]: the trait bound `i32: Drop` is not satisfied
--> src/main.rs:6:20
|
6 | takes_drop(5i32);
| ---------- ^^^^ the trait `Drop` is not implemented for `i32`
| |
| required by a bound introduced by this call
|
note: required by a bound in `takes_drop`
--> src/main.rs:1:22
|
1 | fn takes_drop<T: Drop>(t: T) {
| ^^^^ required by this bound in `takes_drop`
- woodruffw 4y agoThanks for the example! Yeah, I'm realizing my framing (around the Drop trait, and not "droppability" as a concept) was incorrect. Would it be more accurate to say that Rust guarantees the droppability of owned values? I know there's a guarantee that &'static items never have their underlying value dropped, but that works because you can never actually hold the static value itself, only its reference.
- steveklabnik 4y ago> Would it be more accurate to say that Rust guarantees the droppability of owned values? I'm not really sure, exactly, since "droppability" isn't really a thing that's talked about, because as you're sort of getting at here, it's universal, and therefore not really an interesting concept. > I know there's a guarantee that &'static items never have their underlying value dropped, Even this is sort of... not correct. Consider this program: #[derive(Debug)] struct Boom; impl Drop for Boom { fn drop(&mut self) { println!("BOOM"); } } use std::mem; static mut FOO: Boom = Boom; fn main() { let mut s = Boom; unsafe { dbg!(&FOO); mem::swap(&mut FOO, &mut s); dbg!(&FOO); } } This will print BOOM, as the initial Boom is swapped out from behind the reference and then dropped.
- steveklabnik 4y ago(Oh I just realized, for those not super familiar with Rust, mem::swap is safe but since dereferencing FOO is unsafe, I just left in one block, not two.)