Drop and Destruct
The Drop trait only has one method: drop, which is called automatically when an object
goes out of scope. The main use of the Drop trait is to ensure that all dictionaries are
"squashed" when they go out of scope. This "squashing" mechanism ensures that the sequential
accesses to the dictionary are consistent and sound regarding proof generation.
Any type that is not a dictionary can trivially derive the Drop trait.
The [Destruct][Destruct] trait is a more powerful version of the Drop trait. It allows for
the developer to specify what should happen when an object goes out of scope.
All types can trivially derive the Destruct trait, even if they're composed of dictionaries.
The following example adds a print to console to the drop function to announce
when it is called.
use core::dict::Felt252Dict;
#[derive(Destruct)]
struct DestructibleType {
name: ByteArray,
dict: Felt252Dict<u64>,
}
// Try to derive `Drop` instead of `Destruct` and see what happens.
fn main() {
let _a = DestructibleType { name: "a", dict: Default::default() };
// block A
{
let _b = DestructibleType { name: "b", dict: Default::default() };
// block B
{
let _c = DestructibleType { name: "c", dict: Default::default() };
let _d = DestructibleType { name: "d", dict: Default::default() };
println!("Exiting block B");
}
println!("Just exited block B");
println!("Exiting block A");
}
println!("Just exited block A");
println!("end of the main function");
}