rust-lang/rust-by-example

Borrowing (Rust by Example)

bhutta03 opened this issue · 1 comments

There the presented code is wrong
Presented Code
`// This function takes ownership of a box and destroys it
fn eat_box_i32(boxed_i32: Box) {
println!("Destroying box that contains {}", boxed_i32);
}

// This function borrows an i32
fn borrow_i32(borrowed_i32: &i32) {
println!("This int is: {}", borrowed_i32);
}

fn main() {
// Create a boxed i32, and a stacked i32
let boxed_i32 = Box::new(5_i32);
let stacked_i32 = 6_i32;

// Borrow the contents of the box. Ownership is not taken,
// so the contents can be borrowed again.
borrow_i32(&boxed_i32);
borrow_i32(&stacked_i32);

{
    // Take a reference to the data contained inside the box
    let _ref_to_i32: &i32 = &boxed_i32;

    // Error!
    // Can't destroy `boxed_i32` while the inner value is borrowed later in scope.
    eat_box_i32(boxed_i32);
    // FIXME ^ Comment out this line

    // Attempt to borrow `_ref_to_i32` after inner value is destroyed
    borrow_i32(_ref_to_i32);
    // `_ref_to_i32` goes out of scope and is no longer borrowed.
}

// `boxed_i32` can now give up ownership to `eat_box` and be destroyed
eat_box_i32(boxed_i32);

}`

Actual Code(i think so you may check
`// This function takes a reference to a box
fn eat_box_i32(boxed_i32: &Box) {
println!("Destroying box that contains {}", **boxed_i32);
}

// This function borrows an i32
fn borrow_i32(borrowed_i32: &i32) {
println!("This int is: {}", borrowed_i32);
}

fn main() {
// Create a boxed i32, and a stacked i32
let boxed_i32 = Box::new(5_i32);
let stacked_i32 = 6_i32;

// Borrow the contents of the box. Ownership is not taken,
// so the contents can be borrowed again.
borrow_i32(&boxed_i32);
borrow_i32(&stacked_i32);

{
    // Take a reference to the data contained inside the box
    let _ref_to_i32: &i32 = &boxed_i32;

    // Call `eat_box_i32` with a clone of the boxed_i32
    eat_box_i32(&boxed_i32.clone());

    // Attempt to borrow `_ref_to_i32` after inner value is destroyed
    borrow_i32(_ref_to_i32);
    // `_ref_to_i32` goes out of scope and is no longer borrowed.
}

// `boxed_i32` can now give up ownership to `eat_box` and be destroyed
eat_box_i32(&boxed_i32);

}`

Hi, I'm closing this issue just to clean up the items that already exist. If you think this issue makes sense to stay open, please create a new issue with updated information and mention this one.

thanks!