Rust Drop

Drop is a #202204061235 which could be used for automatic resource clean up# when the object or variable is out of scope. It is typically implemented in #202111301656. To implement the trait Drop, we need to implement the method drop for the structure:

impl Drop for MyStruct {
		fn drop(&mut self) {
				println!("Automatic resource clean up for MyStruct");
		}
}

However, we can’t directly call the method drop in order to clean the resource earlier. And there is no way for Rust to disable automatic resource clean up mechanism which even if there is, it is unwise to do so. For that purpose, use std::mem::drop instead. (You can simply call drop({variable}) as it is included in the Rust prelude)

Links to this page
  • Rust Trait
  • Rust Smart Pointers

    Rust standard library implements several smart pointers for better resource cleaned up as they have implemented the 202206221653# 202204061235#. If a reference go out of scope, depending on which kind of smart pointer that it is using, either it will be automatically destroyed or decrements the number of references that is pointing to the referred variable or object. Unlike other programming languages, such rule can be check in compile time if wanted.

  • Reference Counting Pointer

    Rc<T> is a kind of the #202111301656 that share the ownership of the referred variable or object between multiple pointers. Each time when the reference is “borrowed”, it will increment the reference count (using method Rc::clone), and if such count is down to 0, Rc<T> will be destroyed#. This is similar to #cpp shared_ptr with the difference that it allows only reading due to its immutable nature.

#rust #memory #resource