1

I have a structure Game and I want to be able to build an object but with the possibility to remove features at compile time, to optimize memory or processor cycles.

struct Game {
    history: Vec<SomeType>,
}

impl Game {
    fn new() {}

    fn new_opti() {}
}

For example, in this structure the optimized version would have no history. Here, I replaced history with an Option<Vec<SomeType>> and in the optimized version I put a None and I change the behavior of the history dependent methods, and I disable some methods.

I think this is a hacky way, but what would be a better way? There is no need to keep only one struct.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 2
    "Better way" -- in which regard? Can you tell us a bit more about your requirements? I.e. is the size of the struct `Game` important? Is speed a concern? Or is it fine if each time `history` is accessed, we check if it's `None` first? – Lukas Kalbertodt Sep 09 '19 at 22:15
  • 3
    The number one rule of optimisation is that you should never guess about what to optimise. (In most of the situations your guess will be completely wrong.) Build your thing, profile it, and then based on your measurements find out 1. if you need to optimise anything at all, 2. if you do, what exactly you have to optimise, 3. if you find out what you need to optimise whether it make sense to solve it with conditional compilation (which is the behaviour you just described). – Peter Varo Sep 09 '19 at 23:24
  • 3
    Are you looking for a compile-time option, or a runtime one? – Acorn Sep 09 '19 at 23:24
  • 2
    `Option>` takes the same amount of space as `Vec` ([What is the overhead of Rust's Option type?](https://stackoverflow.com/q/16504643/155423)) and it's rare to see it because usually you don't need to distinguish between an empty `Vec` and a `Vec` that isn't present. – Shepmaster Sep 10 '19 at 00:33
  • @LukasKalbertodt A better way like https://softwareengineering.stackexchange.com/questions/356262/handling-optional-features where they propose the strategy pattern. – Samuel B. T. Sep 10 '19 at 08:20
  • @Acorn a compilation one. – Samuel B. T. Sep 10 '19 at 08:26
  • @Shepmaster Good to know ! But for me it's more a way to distinguish if the "feature" is enabled or not. – Samuel B. T. Sep 10 '19 at 08:27
  • It looks like your question might be answered by the answers of [How do I use conditional compilation with `cfg` and Cargo?](https://stackoverflow.com/q/27632660/155423) and If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Sep 10 '19 at 13:21

1 Answers1

1

Since you mentioned in the comments that you want a compile-time answer, you can simply compile the field whenever you choose:

struct Game {    
    #[cfg(foo)]
    history: Vec<SomeType>,

    ...
}

Similarly, you can compile out the code using the field.

Acorn
  • 24,970
  • 5
  • 40
  • 69