Galactus
Galactus

Reputation: 107

Rust language - Drop & Borrow checker

fn testing(myptr :&mut Box<i32>) {
    println!("Fn is called: {}",myptr);
    *myptr=Box::new(300);
    println!("Inside: {}",myptr);
    *myptr=Box::new(0);
    println!("Inside: {}",myptr);
    drop(myptr);
}

fn main() {
    let mut myptr = Box::new(100);
    println!("Before Func: {}",myptr);
    testing(&mut myptr);
    println!("From Main: {}",myptr);
}

output

Before Func: 100
Fn is called: 100
Inside: 300
Inside: 0
From Main: 0

since i have invoked drop function i am expecting the value shouldn't be accessible even from main function but thats not happing. not able to understand why. Need help in understanding who is owning ownership and why drop function is not working.

Upvotes: 2

Views: 257

Answers (1)

kmdreko
kmdreko

Reputation: 60447

The call to drop(myptr) in this context does not drop the Box<i32> it only drops the reference, which is effectively a no-op. You cannot drop something via a reference since it doesn't own the value. And what would the "From Main:" line print?

If you want myptr to be dropped by testing(), then you will have to take ownership of it:

fn testing(myptr: Box<i32>) {
    // myptr will be destroyed at the end of the scope
}

fn main() {
    let myptr = Box::new(100);
    testing(myptr);

    // attempting to use it afterwards will yield a compiler error
    // println!("From Main: {}", myptr);
}

If you want testing() to "nullify" myptr, use an Option:

fn testing(myptr: &mut Option<Box<i32>>) {
    *myptr = None;
}

fn main() {
    let mut myptr = Some(Box::new(100));
    println!("Before Func: {:?}", myptr); // prints "Some(100)"
    testing(&mut myptr);
    println!("From Main: {:?}", myptr); // prints "None"
}

Upvotes: 4

Related Questions