I am new to Rust and I am investigating vector implementation. I tried to resize vector many times and check addresses of elements with following code:
fn main() {
let mut vector = Vec::new();
for i in 1..100 {
println!(
"Capacity:{}, len: {}, addr: {:p}",
vector.capacity(),
vector.len(),
&vector,
);
vector.push(i);
}
println!("{:p}", &vector[90]);
}
It gives me output (last 2 lines):
Capacity:128, len: 98, addr: 0x7ffebe7a6930
addr of 90-element: 0x5608b516bd08
My question is why 90-th element is in another memory location? I assume it should me somewhere near the 0x7ffebe7a6930 address.
Vec::new(), it will pre-allocate some memory, and even if it probably allocates less than 100 elements, it still could allocate more and simply never reallocate. Maybe, for the sake of the experimentation, you should start with aVec::with_capacity(1)or something like that.Vec::new()is documented to not allocate. See the third paragraph here.