内存分布和 C 基本一致,不过还没有找到如何打印变量本身在栈中的位置的方法,也许它已经被完全编译器优化为偏移量了,没有深入研究。 &stu1 的值是结构体的首地址,第一个 String 占用了 0x18 个字节的大小。
以下代码用来通过指针偏移量打印 Student.age 的值。
struct Student {
name: String,
age: i32,
}
fn main() {
let stu1 = Student{name:"1234".into(), age:123};
println!("raw points at {:p}", &stu1); // raw points at 0x7ffeef327268 + 0x18
println!("raw points at {:p}", &stu1.age); // raw points at 0x7ffeef327280
let praw = ((&stu1 as *const Student) as usize + 0x18usize) as *const i32; // i32 i64 u64 usize 都没问题
let raw = unsafe { *praw };
println!("{:p}", praw);
println!("{}", raw);
}
结果:
raw points at 0x7ffeef75c218
raw points at 0x7ffeef75c230
0x7ffeef75c230
123
来源:oschina
链接:https://my.oschina.net/ooxxx/blog/4289895