EN VI

How can I access memory address where Rust stores values?

2024-03-15 03:00:10
How can I access memory address where Rust stores values

I've tried the following code in the Rust playground thinking one of the options would either reveal the memory location where x was stored, or at least throw an error:

fn main() {
    let x = 2;
    let y = &x;

    println!("Value of x: {}", x);
    println!("Value of x: {:?}", &x);
    println!("Value of y: {:?}", y);
    println!("Value of y: {}", *y);
}

Instead, I got this output:

Value of x: 2
Value of x: 2
Value of y: 2
Value of y: 2

Am I totally misunderstanding the way Rust refers to memory locations & the way it dereferences them? Or, is there something funny about the println! macro that I'm missing? Or, just something I'm not getting about the way it allows operations to take place on memory locations?

Solution:

:p is the specifier to print pointer address:

fn main() {
    let x = 2;
    let y = &x;

    println!("Value of x: {}", x);
    println!("Address of x: {:p}", &x);
    println!("Address of y: {:p}", y);
    println!("Value of y: {}", *y);
}

Playground.

Alternatively, convert the references to raw pointers, which show their address on debug:

fn main() {
    let x = 2;
    let y = &x;

    println!("Value of x: {}", x);
    println!("Address of x: {:?}", &x as *const _);
    println!("Address of y: {:?}", y as *const _);
    println!("Value of y: {}", *y);
}
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login