Expected behavior while printing reference and dereference of a variable

33 Views Asked by At

I am new to rust and have this fundamental doubt:

let x = String::from("hello world");
let y = &x;
println!("y: {}", y);
println!("value of x is: {}", *y);

I understand that y is a reference to the value hello world stored in heap. But why do y print the value of x and not the memory location of y. If this is the expected behavior, why do we need to deference and access the value of a variable using * because &x already gives the value of the variable?

0

There are 0 best solutions below