0

I need to do something that in C I would do like this:

int get_x_value() {
    static int x = -1;

    if (x == -1) {
      // Code to calc the value
      x = 5;
    }

    return x;
}

What is the equivalent in Rust?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
Giuseppe
  • 531
  • 1
  • 5
  • 19
  • 1
    This is tricky to do properly, but _there is a crate for that!_. Have a look at [once_cell](https://crates.io/crates/once_cell). – rodrigo Oct 18 '20 at 21:20
  • Since I am trying to learn I would like to know if there is a guide or similar. – Giuseppe Oct 18 '20 at 21:21
  • 1
    Precisely because you are learning, maybe you don't want to get your hands dirty with _unsafe_ code. But every crate from `crates.io` has the source code available to learn from it. Take also look to [`lazy_static`](https://crates.io/crates/lazy_static), another crate you may find useful. – rodrigo Oct 18 '20 at 21:27
  • 4
    So it's clear, C makes it very not obvious, but the code you have is very dangerous in a multithreaded environment. C leaves it up to the developer to know that they need to be careful, but Rust's type checking prevents code like this from being written casually, which is why you end up needing libraries and unsafe code to handle it properly. – loganfsmyth Oct 18 '20 at 21:41
  • 1
    Do the answers to [How do I create a global, mutable singleton?](/q/27791532/3650362) answer your question? (Note that Shepmaster's answer has an appendix about the "global" part that shows a function local `static`.) If not, please [edit] your question to explain the differences. Thanks! – trent Oct 18 '20 at 22:09
  • 1
    [Here's a safe interpretation of the C code using `lazy_static` and a `Mutex`.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=89fbadccd69b62eceddbc40e8161ba47) Locking the mutex ensures that `get_x_value` has exclusive access to `X` while the calculation is being done, until the lock is released and the function returns. – trent Oct 18 '20 at 22:22

0 Answers0