I'm writing a system where I have a collection of Object
s, and each Object
has a unique integral ID. Here's how I would do it in C++:
class Object {
public:
Object(): id_(nextId_++) { }
private:
int id_;
static int nextId_;
}
int Object::nextId_ = 1;
This is obviously not thread_safe, but if I wanted it to be, I could make nextId_
an std::atomic_int
, or wrap a mutex around the nextId_++
expression.
How would I do this in (preferably safe) Rust? There's no static struct members, nor are global mutable variables safe. I could always pass nextId
into the new
function, but these objects are going to be allocated in a number of places, and I would prefer not to pipe the nextId
number hither and yon. Thoughts?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…