which reference to heap allocated point is right?

Viewed 93

Before I read the book, the reference to the heap is like:

let v: Vec<f64> = vec![0.0,  0.707,  1.0,  0.707];
let a: [f64; 4] =     [0.0, -0.707, -1.0, -0.707];

let sv: &[f64] = &v;
let sa: &[f64] = &a;

enter image description here

(from Programming Rust)
sv is a reference to heap so it points to the same address in heap as v.

But I read a article from https://www.net.in.tum.de/fileadmin/bibtex/publications/theses/2018-ixy-rust.pdf .

fn main(){
    let s = String ::from("hello");
    let r = &s;
    let t = s;
    println!("{}", r);
}

(the code can't be run cause it use reference after move)
enter image description here
emmmm, r just point to the address in stack.Yeah, it is a truly reference but reference in rust is pointer (right?).
This image is the same as the above if the value is stack allocated.And it's more nature explaining why can't use borrow later after move.

So, which is corrent?

1 Answers

They are both correct in their own way.

A Vec<T> can be borrowed either as a &Vec<T> or as a &[T]. Likewise, a String can be borrowed either as a &String or as a &str. Rust will automatically coerce (via Deref) the first to the second when the second is expected.

In the first code sample, sv is explicitly declared as a slice. &v initially produces a &Vec<f64>, but this reference is implicitly coerced to a slice so that it can be assigned to sv.

However, in the second code sample, the type of r is not specified. Rust will therefore infer its type to be &String, because coercions don't happen unless they are necessary.

A &Vec<T> and a &String both look like the second picture. A &[T] and a &str that refer to the interior of a Vec<T> or String both look like the first picture.

Related