Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

Rust print struct address

I am attempting to log a structs address when creating the struct and when it is dropped, when I run the below code not only do both structs log the same address, both structs log a different address when being dropped. Is there a correct way to do this?

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);
}

Output:

creating struct 0x7ffef1f96e44
creating struct 0x7ffef1f96e44
destroying struct 0x7ffef1f96e38
destroying struct 0x7ffef1f96e38
question from:https://stackoverflow.com/questions/65834774/rust-print-struct-address

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In new() you're printing the address of x, when new() returns x is moved, so that is no longer the actual address, which is why you see the same address repeated.

See also "Is a returned value moved or not?".

In drop(), you are actually printing the address of the &Self and not Self itself. You need to change &self as *const _ to just self as self is already a reference. Now it correctly prints the two different addresses.

If you then instead try to print the address of s1 and s2 in main() then the addresses match.

impl TestStruct {
    fn new(val: i32) -> Self {
        let x = TestStruct { val };
        x
    }
}

impl Drop for TestStruct {
    fn drop(&mut self) {
        println!("destroying struct {:p}", self);
    }
}

fn main() {
    let s1 = TestStruct::new(1);
    println!("creating struct {:p}", &s1);

    let s2 = TestStruct::new(2);
    println!("creating struct {:p}", &s2);
}

Output:

creating struct 0xb8682ff59c   <- s1
creating struct 0xb8682ff5f4   <- s2
destroying struct 0xb8682ff5f4 <- s2
destroying struct 0xb8682ff59c <- s1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...