title: Is it possible to declare variables procedurally using Rust macros?
body: <p>Basically, there are two parts to this question:</p>
  
  <ol>
  <li><p>Can you pass an unknown identifier to a macro in <a href="http://www.rust-lang.org/" rel="noreferrer">Rust</a>?</p></li>
  <li><p>Can you combine strings to generate new variable names in a Rust macro?</p></li>
  </ol>
  
  <p>For example, something like:</p>
  
  <pre class="lang-rust prettyprint-override"><code>macro_rules! expand(
    ($x:ident) =&gt; (
      let mut x_$x = 0;
    )
  )
  </code></pre>
  
  <p>Calling expand!(hi) obvious fails because hi is an unknown identifier; but can you somehow do this?</p>
  
  <p>ie. The equivalent in C of something like:</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #define FN(Name, base) \
    int x1_##Name = 0 + base; \
    int x2_##Name = 2 + base; \
    int x3_##Name = 4 + base; \
    int x4_##Name = 8 + base; \
    int x5_##Name = 16 + base;
  
  int main() {
    FN(hello, 10)
    printf("%d %d %d %d %d\n", x1_hello, x2_hello, x3_hello, x4_hello, x5_hello);
    return 0;
  }
  </code></pre>
  
  <p>Why you say, what a terrible idea. Why would you ever want to do that?</p>
  
  <p>I'm glad you asked!</p>
  
  <p>Consider this rust block:</p>
  
  <pre class="lang-rust prettyprint-override"><code>{
     let marker = 0;
     let borrowed = borrow_with_block_lifetime(data, &amp;marker); 
     unsafe {
        perform_ffi_call(borrowed);
     }
  }
  </code></pre>
  
  <p>You now have a borrowed value with an explicitly bounded lifetime (marker) that isn't using a structure lifetime, but that we can guarantee exists for the entire scope of the ffi call; at the same time we don't run into obscure errors where a <code>*</code> is de-referenced unsafely inside an unsafe block and so the compiler doesn't catch it as an error, despite the error being made <em>inside a safe block</em>. </p>
  
  <p>(see also <a href="https://stackoverflow.com/questions/23053398/why-are-all-my-pointers-pointing-to-the-same-place-with-to-c-str-in-rust">Why are all my pointers pointing to the same place with to_c_str() in rust?</a>) </p>
  
  <p>The use a macro that can declare temporary variables for this purpose would considerably ease the troubles I have fighting with the compiler. That's why I want to do this.</p>