Does Rust track unique object ids and can we print them?

心不动则不痛 提交于 2019-12-11 03:38:24

问题


Does Rust use some kind of instance id for each object behind the scenes and if so, can it be made visible?

Consider this

struct SomeStruct;

fn main() {
    let some_thing = SomeStruct;
    println!("{:UniqueId}", some_thing);
    let another = some_thing;
    println!("{:UniqueId}", another);
}

I'm using a pseudo format string with {:UniqueId} here. In this case it may print

4711
4712

I know that Rust makes a bitwise copy and I want to make that actually visible. If I had such an instance id I could make it visible by comparing ids.

There may be an alternative way to achieve the same though.


回答1:


No, Rust does not have any automatically generated ID for objects. That kind of functionality would incur some overhead for every user, and Rust wants to impose as little overhead as it needs to. Everything else should be opt-in.


As far as I know, the address of an item is as unique as you can get:

struct SomeStruct;

fn main() {
    let some_thing = SomeStruct;
    println!("{:p}", &some_thing);
    let another = some_thing;
    println!("{:p}", &another);
}
0x7ffc020ba638
0x7ffc020ba698

Everything1 takes up space somewhere, so you can get the address of that space and print that.

This might be too unique for some cases. For example, when you transfer ownership of an item, you might expect that the ID stays the same. I think in that case, you'd have to roll your own. Something like a global atomic variable that you can pull from when you create the object. Such a scheme won't apply to objects you don't control.


1 — Well, almost everything. I know that const items aren't guaranteed to have a location, which is why static items exist.



来源:https://stackoverflow.com/questions/30157258/does-rust-track-unique-object-ids-and-can-we-print-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!