Option< ...>类型的全局变量在Rust

时间:2016-06-08 17:41:32

标签: rust global

我无法使用以下代码:

error: mutable statics are not allowed to have destructors [E0397]
static mut appWindow: Option<Window> = None;

编译器产生错误:

unsafe { ... }

使用define(['N/ui/serverWidget', 'N/log', 'N/file', './profiler'], function(serverWidget, log, file, profiler) { function onRequest(context) { log.debug('profiler', profiler) // --> logs undefined 包围所有内容无济于事。

1 个答案:

答案 0 :(得分:3)

以下是重现您所显示错误的代码:

error: mutable statics are not allowed to have destructors [E0397]
static mut f: Foo = Foo;
                    ^~~

error: statics are not allowed to have destructors [E0493]
static mut f: Foo = Foo;
                    ^~~

产生错误:

#![feature(drop_types_in_const)]

正如消息所说,Rust不允许任何带有析构函数的静态项。建议的change to the language讨论了这个的起源:

  

这在历史上受到何时运行的问题的推动   析:

     
      
  • 在主要()之前/之后支持生活的担忧,例如静态变量,因为它们历史上一直带来麻烦   例如,在C ++代码库中。
  •   
  • 由于泄漏可能是坏的,因此泄漏析构函数也是最不被认为是可行的选择。
  •   

RFC 1440已被接受允许这些类型。从Rust 1.9开始,有一个不稳定的功能允许它们:var rd = readline.createInterface({ input: fs.createReadStream('/path/to/file'), output: process.stdout, terminal: false }); rd.on('line', function(line) { console.log(line); });

正如RFC所说:

  

析构函数不会在静态项目上运行(按设计),因此当类型的析构函数在程序外部具有效果时(例如RAII临时文件夹句柄,删除文件夹中的文件夹),这会导致意外行为。但是,使用lazy_static包可以发生这种情况。

这导致在功能稳定之前的替代解决方案:您可以使用lazy_static创建一个不可变的静态变量,然后可以将其包装在线程安全的可变性包装器中。该类型可能包含析构函数:

How do I create a global, mutable singleton?