Rust 锈迹打印结构地址
我试图在创建结构时记录结构地址,当它被删除时,当我运行下面的代码时,不仅两个结构记录相同的地址,而且两个结构在被删除时记录不同的地址。有没有正确的方法可以做到这一点Rust 锈迹打印结构地址,rust,Rust,我试图在创建结构时记录结构地址,当它被删除时,当我运行下面的代码时,不仅两个结构记录相同的地址,而且两个结构在被删除时记录不同的地址。有没有正确的方法可以做到这一点 struct TestStruct { val: i32 } impl TestStruct { fn new(val: i32) -> Self { let x = TestStruct{val}; println!("creating struct {:p}&qu
struct TestStruct {
val: i32
}
impl TestStruct {
fn new(val: i32) -> Self {
let x = TestStruct{val};
println!("creating struct {:p}", &x as *const _);
x
}
}
impl Drop for TestStruct {
fn drop(&mut self) {
println!("destroying struct {:p}", &self as *const _)
}
}
fn main() {
let s1 = TestStruct::new(1);
let s2 = TestStruct::new(2);
}
输出:
creating struct 0x7ffef1f96e44
creating struct 0x7ffef1f96e44
destroying struct 0x7ffef1f96e38
destroying struct 0x7ffef1f96e38
creating struct 0xb8682ff59c <- s1
creating struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff59c <- s1
在new()
中,您正在打印x
的地址,当new()
返回x
时,该地址已被移动,因此不再是实际地址,这就是您看到重复相同地址的原因
另见
在drop()
中,您实际上是在打印&Self
的地址,而不是Self
本身。您需要将&self as*const
更改为self
,因为self
已经是一个引用。现在它正确地打印了两个不同的地址
如果您随后尝试在main()
中打印s1
和s2
的地址,则地址匹配
impl TestStruct{
fn新(val:i32)->自{
设x=TestStruct{val};
x
}
}
TestStruct的impl Drop{
fn下降(&mut自我){
println!(“销毁结构{:p}”,self);
}
}
fn main(){
设s1=TestStruct::new(1);
println!(“创建结构{:p},&s1);
设s2=TestStruct::new(2);
println!(“创建结构{:p},&s2);
}
输出:
creating struct 0x7ffef1f96e44
creating struct 0x7ffef1f96e44
destroying struct 0x7ffef1f96e38
destroying struct 0x7ffef1f96e38
creating struct 0xb8682ff59c <- s1
creating struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff59c <- s1
创建结构0xb8682ff59c