What's the idiomatic way to generate a unique sequential i32 ids in new struct instances

Hi. I want my struct to contain a unique i32 in a private field. I'll use them as ids. The code below requires unsafe block:

mod MyTypes {
    static mut COUNTER: i32 = 0;

    pub struct MyStruct {
        id: i32,
    }

    impl MyStruct {
        fn new() -> Self {
            COUNTER += 1;
            Self { id: COUNTER }
        }
    }
}

Now of course, I can create unix timestamps in the constructor method and use them as ids but are there any other methods?

Use atomic integers. Your current code does not guarantee unique ids in multi-threaded code, which is why it requires unsafe, and using it from multi-threaded code would be undefined behaviour because of data races.

4 Likes