Static field in struct and ID generation


#1

Hi,

According to this issue and this post it seems that is not possible to define a static field in a struct.

For example suppose that you are using one of the creational patterns for creating objects that have unique ID. The creational pattern should use a static mut variable used to keep track of last assigned ID (that will be increased it in unsafe way), this variable will be declared somewhere outside the struct that actually is using and could be visible/accessible by other function.

In my point of view there are three problems with this approach:

  1. Unsafe code is needed to increment the variable.
  2. Data racing, since unsafe code is executed (for example I noticed this problem running some tests that I’ve prepared and I found out that cargo test runs each test function in a separated thread by default)
  3. The struct depends on a variable that is not encapsulated in itself and it is accessible by all items of the same module.

I think that there should be a better solution than this one… Could you help me?

Thank you.


#2

You might find this useful: https://crates.io/crates/snowflake


#3

Thank you for your suggestion. I’m trying to using it, but I got some trouble related to another topic, anyway I gave it a quick overview, but it looks a little complex to me, I was expecting something quite straightforward, but maybe this is the cost that you have to pay to assure thread safety for static mutable variables access.


#4

The implementation is complex, mostly for performance reasons. Using it, however, is simple; just call ProcessUniqueId::new().


#5

Just a little question more, so the ID is composed by usize + u64 fields, that means that two ID are equals if both fields are equal?
Anyway I saw that it is implementing the Eq trait, so I can use the == operator and don’t bother about how it’s implemented.

Thank you.


#6

Yes to all. Don’t introspect, just use id1 == id2.