且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在 Rust 中使用全局变量?

更新时间:2023-11-14 10:17:16

是可以的,但是不能直接分配堆.堆分配在运行时执行.以下是一些示例:

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,
}