title: Is it possible to use global variables in Rust?
body: <p>I know that in general, global-variables are to be avoided. Nevertheless, I think in a practical sense, it is sometimes desirable (in situations where the variable is integral to the program) to use them.</p>
  
  <p>In order to learn Rust, I'm currently writing a database test program using sqlite3 and the Rust/sqlite3 package on GitHub. Consequently, that necessitates (in my test-program) (as an alternative to a global variable), to pass the database variable between functions of which there are about a dozen. An example is below.</p>
  
  <ol>
  <li><p>Is it possible and feasible and desirable to use global variables in Rust?</p></li>
  <li><p>Given the example below, can I declare and use a global variable?</p></li>
  </ol>
  
  
  
  <pre><code>extern crate sqlite;
  
  fn main() {
      let db: sqlite::Connection = open_database();
  
      if !insert_data(&amp;db, insert_max) {
          return;
      }
  }
  </code></pre>
  
  <p>I tried the following, but it doesn't appear to be quite right and resulted in the errors below (I tried also with an <code>unsafe</code> block):</p>
  
  <pre><code>extern crate sqlite;
  
  static mut DB: Option&lt;sqlite::Connection&gt; = None;
  
  fn main() {
      DB = sqlite::open("test.db").expect("Error opening test.db");
      println!("Database Opened OK");
  
      create_table();
      println!("Completed");
  }
  
  // Create Table
  fn create_table() {
      let sql = "CREATE TABLE IF NOT EXISTS TEMP2 (ikey INTEGER PRIMARY KEY NOT NULL)";
      match DB.exec(sql) {
          Ok(_) =&gt; println!("Table created"),
          Err(err) =&gt; println!("Exec of Sql failed : {}\nSql={}", err, sql),
      }
  }
  </code></pre>
  
  <p>Errors that resulted from compile:</p>
  
  <pre class="lang-none prettyprint-override"><code>error[E0308]: mismatched types
   --&gt; src/main.rs:6:10
    |
  6 |     DB = sqlite::open("test.db").expect("Error opening test.db");
    |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected enum `std::option::Option`, found struct `sqlite::Connection`
    |
    = note: expected type `std::option::Option&lt;sqlite::Connection&gt;`
               found type `sqlite::Connection`
  
  error: no method named `exec` found for type `std::option::Option&lt;sqlite::Connection&gt;` in the current scope
    --&gt; src/main.rs:16:14
     |
  16 |     match DB.exec(sql) {
     |              ^^^^
  </code></pre>