How pointers are placed in stack

In Rust,

  • Vec has a data on the heap and the ownership pointer has three metadata (pointer, capacity and the length) and placed on the stack.
  • Slice is a fat pointer with two members (pointer and length) and placed on the stack.

And data will be destroyed when the ownership pointer is going out of scope, which is generally called RAII.

These are textbook knowledge and you can find from any books but I couldn't find anything about how fat pointer is placed. So in this article, we will have a simple experiment.

fn main() {
    let v: Vec<i32> = vec![1,2,3,4,5,6,7,8,9,10];
    let vv: &[i32] = &v;
    let vvv: &&[i32] = &vv;
    println!("{:p}, {}", &v, mem::size_of::<Vec<i32>>());
    println!("{:p}, {}", &vv, mem::size_of::<&[i32]>());
    println!("{:p}, {}", &vvv, mem::size_of::<&&[i32]>());

And the output is:

0x7ffcf237a7f8, 24
0x7ffcf237a7e8, 16
0x7ffcf237a7e0, 8

We can think of this output as the pointers are placed like this.