title: Dealing with so-called global variables in Rust
body: <p>We all know that using global variables can lead to subtle bugs. I need to migrate Python programs to Rust, keeping the algorithm intact as far as possible. Once I have demonstrated Python-Rust equivalence there will be opportunities to debug and change the logic to fit Rust better.  Here is a simple Python program using global variables, followed by my unsuccessful Rust version.</p>
  <pre class="lang-python prettyprint-override"><code># global variable 
  a = 15
  
  # function to perform addition 
  def add(): 
      global a
      a += 100
  
  # function to perform subtraction
  def subtract(): 
      global a
      a -= 100
  
  # Using a global through functions
  print(&quot;Initial value of a  = &quot;, a)
  add() 
  print(&quot;a after addition   = &quot;, a)
  subtract() 
  print(&quot;a after subtraction = &quot;, a)
  </code></pre>
  <p>Here is a Rust program that runs, but I cannot get the closures to update the so-called global variable.</p>
  <pre class="lang-rust prettyprint-override"><code>fn fmain() {
  // global variable 
      let mut a = 15;
  
  // perform addition 
      let add = || {
          let mut _name = a;
  //        name += 100;  // the program won't compile if this is uncommented
      };
  
      call_once(add);
  
  //  perform subtraction
      let subtract = || {
          let mut _name = a;
  //        name -= 100;  // the program won't compile if this is uncommented
      };
  
      call_once(subtract);
  
      // Using a global through functions
      println!(&quot;Initial value of a    = {}&quot;, a);
      add();
      println!(&quot;a after addition      = {}&quot;, a);
      subtract();
      println!(&quot;a after subtraction   = {}&quot;, a);
  }
  
  fn main() {
      fmain();   
  }
  
  fn call_once&lt;F&gt;(f: F)
  where
      F: FnOnce(),
  {
      f();
  }
  </code></pre>
  <p>My request: Re-create the Python logic in Rust.</p>