fasterthanlime / feedback

An issue tracker for articles/series/videos at https://fasterthanli.me/
13 stars 0 forks source link

A half-hour to learn Rust #266

Closed intervall-daniel closed 6 months ago

intervall-daniel commented 1 year ago

I found something (wrong) on this page: https://fasterthanli.me/articles/a-half-hour-to-learn-rust#position=4.3

Here's what it is:

let x = 13; let x = x + 3; // using x after that line only refers to the second x, // the first x no longer exists.

I tested in what way the "original" x lives on:

fn main() {
    //Original x
    let x: i32 = 42;
    let address_x = &x as *const i32;
    println!("Shadow value of x             : {}", x);
    println!("Address of x                  : {:p}", address_x);

    //Shadowed x
    let x = 137;
    let new_address_x = &x as *const i32;
    println!("Shadowed value of x           : {}", x);
    println!("Changed address of x          : {:p}", new_address_x);

    //Original x lives on in memory
    unsafe {
        println!();
        let value_at_address_x = *address_x;
        println!("Value at address {:?}  : {}", address_x, value_at_address_x);
        let value_at_new_address_x = *new_address_x;
        println!("Value at address {:?}  : {}", new_address_x, value_at_new_address_x);
    }
}

this is the output one gets:

Shadow value of x             : 42
Address of x                  : 0x16b4629e4
Shadowed value of x           : 137
Changed address of x          : 0x16b462a74

Value at address 0x16b4629e4  : 42
Value at address 0x16b462a74  : 137
fasterthanlime commented 6 months ago

You were right! I fixed the article.