Open In App

Rust – RAII Enforcement

Last Updated : 11 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of RAII where RAII stands for Resource Acquisition is Initialisation.

RAII in Rust is a design pattern where we initialize resources in Rust (happens in the constructor) and then the object is finalized in the destructor. In this design pattern, the RAII object provides a guard for all the resources and the resources which rely on the type system. RAII always ensures that resource access is always mediated by none other than guard objects.

In Rust, apart from holding data in stack, they also own the resources. RAII is implemented in scenarios whenever an object (in the memory) goes out of scope. The owned resources are freed whenever the object reaches beyond its scope. RAII’s strict implementation allows the code to have fewer memory leaks thereby removing the necessity of freeing the memory manually.

Example 1:  

Rust




// Rust program for RAIL Enforcement
fn gfg_box() 
 {
    let _gfg1 = Box::new(5i32);
 }
      
fn main() 
 {
    let _gfg2 = Box::new(7i32);
    println!("Allocating _gfg2 on heap");
    {
      let _gfg3 = Box::new(6i32);
      println!("_gfg3 memory is freed!");
    }
 }


Output:

 

Explanation:

In this example, we have created a Box named gfg_box. As per RAII rules, we have allocated an integer (_gfg1) on the heap by using Box::new() and it takes an integer of 5 widths (unsigned). In this scope, _gfg1 gets destroyed and the memory is freed from the heap. In the main function, we create another variable (_gfg2) that is given a width of 7(unsigned). Here, again_gfg3 is destroyed in this scope and the memory is freed from the heap.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads