Rust Programming2026-02-27 01:00

How to declare different methods based on type parameters

rustfan
rustfan
Author

I have a struct Player with some general attributes, including the Strategy attribute, which is a struct on its own. My question is how can I impl different methods based on which strategy is chosen? I am looking for a way of doing this on-construction, since the Strategy attribute is constant. I am currently using a general impl block with a match statement like this:

impl Player {
    //The vector is a global variable that keeps track of the decisions
    fn take_turn(self: Player, turns_vector: Vec<(bool,bool)) -> bool {
        match self.strategy {
            Strategy::strategy1 => {//Some code...},
            Strategy::strategy2 => {//Some more code...}
        }
    }
}

But if I understand it correctly, this needs to evaluate on every turn, so I am wondering if there is a way to declare the method once for the particular object and always use that one.

36

Comments (0)

Login to comment

Login Now

Loading comments...