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
254 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


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

...