Hi, I am trying to grasp why the following may need / must use a Pin
, but I am not being able to follow the though process.
#[derive(Debug)]
struct A {
a: Vec<u32>,
b: *const u8,
}
impl A {
fn new(a: Vec<u32>) -> Self {
let b = a.as_ptr() as *const u8;
Self {
a,
b,
}
}
pub fn as_slice(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.b, self.a.len() * 4) }
}
pub fn vec_ptr(&self) -> *const u32 {
self.a.as_ptr()
}
}
fn main() {
let mut a = A::new(vec![1, 2]);
let mut b = A::new(vec![3, 4]);
println!("a: {:?}, {:?}", a, a.vec_ptr());
println!("b: {:?}, {:?}", b, b.vec_ptr());
println!("swap");
std::mem::swap(&mut a, &mut b);
println!("a: {:?}, {:?}", a, a.vec_ptr());
println!("b: {:?}, {:?}", b, b.vec_ptr());
drop(a);
println!("b: {:?}, {:?}", b, b.vec_ptr());
}
Output
a: A { a: [1, 2], b: 0x55954512ead0 }, 0x55954512ead0
b: A { a: [3, 4], b: 0x55954512eaf0 }, 0x55954512eaf0
swap
a: A { a: [3, 4], b: 0x55954512eaf0 }, 0x55954512eaf0
b: A { a: [1, 2], b: 0x55954512ead0 }, 0x55954512ead0
b: A { a: [1, 2], b: 0x55954512ead0 }, 0x55954512ead0
The prints indicate that there is consistency between the pointer A::b
and the corresponding address A::vec_ptr
, no?
(For the purposes of this exercise, we can assume that A::a
is immutable; i.e. it does not grow or shrink)