36
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

lazy_staticはもう古い。遅延初期化にはonce_cellを使おう

Last updated at Posted at 2020-11-16

目に訴える1

lazy_staticマクロを使っていますし、BACKTRACEの本当の型がわかりません。

use lazy_static::lazy_static;

// `BACKTRACE` implements `Deref<Target = Option<String>>` 
// and is initialized on the first access
lazy_static! {
    static ref BACKTRACE: Option<String> = std::env::var("RUST_BACKTRACE").ok();
}

once_cellは通常のRustの文法の範囲内ですし、BACKTRACEの型も明示的に書かれています。

use std::sync::Lazy;

// `BACKTRACE` implements `Deref<Target = Option<String>>` 
// and is initialized on the first access
static BACKTRACE: Lazy<Option<String>> = Lazy::new(|| {
    std::env::var("RUST_BACKTRACE").ok()
});

権威に訴える

Nightlyの標準ライブラリには既に遅延初期化に関するAPIが入っていますがこれはonce_cellクレートからコピーされたものです。

The proposed API is directly copied from once_cell crate.

作者が訴える

once_cellの作者がlazy_staticに取って代わるものだと言っています。

Add support for lazy initialized values to standard library, effectively superseding the popular lazy_static crate.

結論を訴える

once_cellを使いましょう。

  1. コード例はRFCのプルリクからパクってきています。

36
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?