title: How do I keep internal state in a WebAssembly module written in Rust?
body: <p>I want to do computations on a large set of data each frame of my web app. Only a subset of this will be used by JavaScript, so instead of sending the entire set of data back and forth between WebAssembly and JavaScript each frame, it would be nice if the data was maintained internally in my WebAssembly module.</p>
  
  <p>In C, something like this works:</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;emscripten/emscripten.h&gt;
  
  int state = 0;
  
  void EMSCRIPTEN_KEEPALIVE inc() {
      state++;
  }
  
  int EMSCRIPTEN_KEEPALIVE get() {
      return state;
  }
  </code></pre>
  
  <p>Is the same thing possible in Rust? I tried doing it with a <code>static</code> like this:</p>
  
  <pre><code>static mut state: i32 = 0;
  
  pub fn main() {}
  
  #[no_mangle]
  pub fn add() {
      state += 1;
  }
  
  #[no_mangle]
  pub fn get() -&gt; i32 {
      state
  }
  </code></pre>
  
  <p>But it seems <code>static</code> variables cannot be mutable.</p>