私は一般的に、グローバル変数は避けなければならないことを知っています。それにもかかわらず、実際の意味では、(変数がプログラムに不可欠な状況では)それらを使用することが望ましいことがあると私は思っています。Rustでグローバル変数を使用することはできますか?
私は現在、Rustを学ぶために、sqlite3とGitHubのRust/sqlite3パッケージを使用してデータベーステストプログラムを作成しています。したがって、これは(私のテストプログラムでは)(グローバル変数の代わりに)約十数個の関数間でデータベース変数を渡す必要があります。以下に例を示します。
グローバル変数を使用することは可能ですか?
以下の例では、グローバル変数を宣言して使用できますか?
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) {
| ^^^^
**安全**解決のために、どのように私はグローバルに作成します[参照してください。 、mutable singleton?](http://stackoverflow.com/q/27791532/155423)。 – Shepmaster