是否有可能在Rust中使用全局变量? [英] Is it possible to use global variables in Rust?
问题描述
-
在Rust中使用全局变量是否可行也是可行和可行的?
-
给出下面的例子,我可以声明并使用一个全局变量吗?
extern crate sqlite;
fn main(){
let db:sqlite :: Connection = open_database();
if!insert_data(& db,insert_max){
return;
$ / code $ / pre
我尝试了以下,但它没有出现(我尝试了 unsafe
block): extern crate sqlite;
static mut DB:Option< sqlite :: Connection> =无;
fn main(){
DB = sqlite :: open(test.db)。expect(Error open test.db);
println!(Database Opened OK);
create_table();
println!(已完成);
$ b $ //创建表
fn create_table(){
let sql =CREATE TABLE IF NOT EXISTS TEMP2(ikey INTEGER PRIMARY KEY NOT NULL);
匹配DB.exec(sql){
Ok(_)=> println!(创建表),
Err(err)=> println!(Exec of Sql failed:{} \\\
Sql = {},err,sql),
}
}
编译产生的错误:
$ b
错误[E0308]:不匹配的类型
- > src / main.rs:6:10
|
6 | DB = sqlite :: open(test.db)。expect(Error open test.db);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^预期enum`std :: option :: Option`,找到struct`sqlite :: Connection`
|
= note:期望的类型`std :: option :: Option< sqlite :: Connection>`
找到的类型`sqlite :: Connection`
错误:在当前作用域中为`std :: option :: Option< sqlite :: Connection>`类型找到的exec`
- > src / main.rs:16:14
|
16 |匹配DB.exec(sql){
| ^^^^
解决方案这是可能的,但不允许堆分配直。堆分配在运行时执行。这里有几个例子:
static SOME_INT:i32 = 5;
static SOME_STR:&'static str =一个静态字符串;
static SOME_STRUCT:MyStruct = MyStruct {
number:10,
string:Some string,
};
static mut db:Option< sqlite :: Connection> =无;
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,
}
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.
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.
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;
}
}
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 : {}\nSql={}", err, sql),
}
}
Errors that resulted from compile:
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 no heap allocation allowed directly. Heap allocation is performed at runtime. Here are 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屋!