161

一般に、グローバル変数は避けるべきであることを私は知っています。それでも、実用的な意味では、(変数がプログラムに不可欠な状況では)それらを使用することが望ましい場合があると思います。

Rust を学ぶために、現在 GitHub で sqlite3 と Rust/sqlite3 パッケージを使用してデータベース テスト プログラムを作成しています。その結果、(私のテストプログラムでは) (グローバル変数の代わりとして) 12 ほどある関数間でデータベース変数を渡す必要があります。以下に例を示します。

  1. Rustでグローバル変数を使用することは可能で実行可能であり、望ましいですか?

  2. 以下の例では、グローバル変数を宣言して使用できますか?

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) {
   |              ^^^^
4

5 に答える 5

100

可能ですが、ヒープ割り当てを直接許可することはできません。ヒープ割り当ては実行時に実行されます。以下にいくつかの例を示します。

static SOME_INT: i32 = 5;
static SOME_STR: &'static str = "A static string";
static SOME_STRUCT: MyStruct = MyStruct {
    number: 10,
    string: "Some string",
};
static mut db: Option<sqlite::Connection> = None;

fn main() {
    println!("{}", SOME_INT);
    println!("{}", SOME_STR);
    println!("{}", SOME_STRUCT.number);
    println!("{}", SOME_STRUCT.string);

    unsafe {
        db = Some(open_database());
    }
}

struct MyStruct {
    number: i32,
    string: &'static str,
}
于 2013-10-26T16:20:34.197 に答える
34

Rust bookのconstandstaticセクションを見てください。

次のようなものを使用できます。

const N: i32 = 5;

また

static N: i32 = 5;

グローバル空間で。

しかし、これらは可変ではありません。可変性については、次のようなものを使用できます。

static mut N: i32 = 5;

次に、それらを次のように参照します。

unsafe {
    N += 1;

    println!("N: {}", N);
}
于 2016-05-20T11:25:25.503 に答える