ADVERTISEMENT
ADVERTISEMENT

Rust program to demonstrate the de-referencing of the dynamically allocated variable

Rust Example: Write a program to demonstrate the de-referencing of the dynamically allocated variable.
Submitted by Nidhi, on November 25, 2021

Problem Solution:

In this program, we will create a variable that will allocate space into the HEAP area of memory using the Box::new() function, and then we will use the "*" dereferencing operator to access the value of the created variable.

Program/Source Code:

The source code to demonstrate the de-referencing of dynamically allocated variables is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to demonstrate the de-referencing 
// of dynamically allocated variable

fn main() {
    let number = Box::new(5); 
    
    // if number == 5 
    // Above statement - generate error that's
    // why dereferencing is required
    
    if *number == 5
    {
        println!("Hello");
    }
    else
    {
        println!("Hiiii");
    }
}

Output:

Hello

Explanation:

In the main() function, we used Box::new() function to create a variable in the HEAP area of memory. Then we used the "*" dereferencing operator to access the value of the created variable and printed the appropriate message based on the if condition.

Rust Miscellaneous Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.