是否可以在 Rust 中使用全局变量? [英] Is it possible to use global variables in Rust?
问题描述
我知道一般来说,应该避免使用全局变量.尽管如此,我认为在实际意义上,有时(在变量对程序不可或缺的情况下)使用它们是可取的.
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.
为了学习 Rust,我目前正在使用 GitHub 上的 sqlite3 和 Rust/sqlite3 包编写数据库测试程序.因此,这需要(在我的测试程序中)(作为全局变量的替代方案)在大约有十几个函数之间传递数据库变量.下面是一个例子.
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.
在 Rust 中使用全局变量是否可行、可行和可取?
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;
}
}
我尝试了以下操作,但似乎不太正确并导致以下错误(我也尝试使用 unsafe
块):
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 : {}
Sql={}", 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) {
| ^^^^
推荐答案
是可以的,但是不能直接分配堆.堆分配在运行时执行.以下是一些示例:
It's possible, but heap allocation is not allowed directly. Heap allocation is performed at runtime. Here are a few examples:
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,
}
这篇关于是否可以在 Rust 中使用全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!