0

In javascript we can use the static keyword to define a static method or property for a class. Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself. So, for instance, we could count the number of instances of a certain class we've created:

class Player{
    static playerCount = 0;

    constructor(){
        Player.playerCount ++;
    }

}

Is their anything in rust that would roughly equivalent to this? Or possibly a library/macro that allows for something similar?

struct Player{}
impl Player{
    static playerCount;
    pub fn new()->Self{
        playerCount ++
        //increment playerCount 
    }
}

1
  • 2
    Rust does not support static fields in structures Commented Jun 9, 2021 at 2:07

1 Answer 1

1

There isn't such a thing as a static field in a Rust struct. Rust's structs are closer to their C namesake than the classes you'd find in object-oriented languages.

The rough equivalent is probably a static mut variable, which requires the use of unsafe code. This is because a globally accessible, mutable value is going to be a source of undefined behavior (such as data races) and Rust wants all code to be free of UB unless you write the word unsafe.

For your use case, perhaps a PlayerManager struct which holds this state and is passed by &mut reference to the new function is a good idea.

struct PlayerManager {
    count: usize,
}

impl PlayerManager {
    pub fn add_player(&mut self) {
        self.count += 1;
    }
}

// then...
impl Player {
    pub fn new(manager: &mut PlayerManager) -> Self {
        manager.add_player();
        // TODO: the rest of player construction
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I was thinking that some kind of Manager struct would be my next recourse. Any chance you could add some example code that illustrates your description of PlayerManger?
@ANimator120 I've added an example, but it's fairly simplistic (and was initially left out since I didn't think it was needed for this answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.