一般に、グローバル変数は避けるべきであることを私は知っています。それでも、実用的な意味では、(変数がプログラムに不可欠な状況では)それらを使用することが望ましい場合があると思います。
Rust を学ぶために、現在 GitHub で sqlite3 と Rust/sqlite3 パッケージを使用してデータベース テスト プログラムを作成しています。その結果、(私のテストプログラムでは) (グローバル変数の代わりとして) 12 ほどある関数間でデータベース変数を渡す必要があります。以下に例を示します。
Rustでグローバル変数を使用することは可能で実行可能であり、望ましいですか?
以下の例では、グローバル変数を宣言して使用できますか?
extern crate sqlite;
fn main() {
let db: sqlite::Connection = open_database();
if !insert_data(&db, insert_max) {
return;
}
}
私は次のことを試しましたが、まったく正しくないようで、以下のエラーが発生しました(unsafe
ブロックでも試しました):
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),
}
}
コンパイルに起因するエラー:
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) {
| ^^^^