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.
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.
Is it possible and feasible and desirable to use global variables in Rust?
Given the example below, can I declare and use a global variable?
extern crate sqlite;
fn main() {
let db: sqlite::Connection = open_database();
if !insert_data(&db, insert_max) {
return;
}
}
I tried the following, but it doesn't appear to be quite right and resulted in the errors below (I tried also with an unsafe
block):
extern crate sqlite;
static mut DB: Option<sqlite::Connection> = 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(_) => println!("Table created"),
Err(err) => println!("Exec of Sql failed : {}\nSql={}", err, sql),
}
}
Errors that resulted from compile:
error[E0308]: mismatched types
--> 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<sqlite::Connection>`
found type `sqlite::Connection`
error: no method named `exec` found for type `std::option::Option<sqlite::Connection>` in the current scope
--> src/main.rs:16:14
|
16 | match DB.exec(sql) {
| ^^^^
Connection
inside anOption<Connection>
type, and trying to use anOption<Connection>
as aConnection
. If those errors were resolved (by usingSome()
) and they used anunsafe
block, as they originally tried, their code would work (albeit in a thread-unsafe way). – TheHans255