Home »
Rust »
Rust Programs
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 »