我知道一般来说应该避免使用全局变量。然而,在实际情况下,如果变量对于程序至关重要,有时使用它们是可取的。
为了学习Rust,我正在使用sqlite3和GitHub上的Rust/sqlite3软件包编写一个数据库测试程序。因此,这就需要(在我的测试程序中)将数据库变量在大约十几个函数之间传递(作为全局变量的替代方案)。以下是示例。
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) {
| ^^^^
Connection
存储在Option<Connection>
类型中以及尝试将Option<Connection>
用作Connection
有关。如果通过使用Some()
解决了这些错误并且像他们最初尝试的那样使用了一个unsafe
块,则他们的代码将工作(虽然是线程不安全的方式)。 - TheHans255