rust初始化全局变量

编写项目需要在程序运行时就初始化一个全局变量供后面使用,采用了lazy_static

  • 修改cargo.toml文件,加入依赖
[dependencies]
lazy_static = "1.4.0"
  •  在main.rs文件中使用

#[macro_use]
extern crate lazy_static;
  • 在main方法中加入
lazy_static! {
    static ref TEMPLATE: Template = {
        let (certificate_template, template_private_key) =
            issuer_init_certificate_template();
        Template {
            certificate_template: certificate_template,
            template_private_key: template_private_key,
        }
    };
}
  • 使用
println!("模板是{:?}", TEMPLATE.certificate_template);

你可能感兴趣的:(rust,rust,开发语言,后端)