4 releases

Uses old Rust 2015

0.2.1 Aug 1, 2024
0.2.0 May 2, 2018
0.1.1 Apr 30, 2018
0.1.0 Apr 30, 2018

#1410 in Rust patterns

Download history 7/week @ 2024-07-22 110/week @ 2024-07-29 4/week @ 2024-08-05 29/week @ 2024-09-09 6/week @ 2024-09-16 14/week @ 2024-09-23 3/week @ 2024-09-30 3/week @ 2024-10-14 20/week @ 2024-10-21 26/week @ 2024-10-28 13/week @ 2024-11-04

62 downloads per month

MIT license

10KB
167 lines

lateinit

Docs Latest

Disclaimer: this crate breaks Rust's safety guarantees. I strongly recommend using static_cell instead in almost all cases. In case that doesn't meet your needs, consider spin::Once, std::sync::Once, or lazy_static instead.

[dependencies]
lateinit = "0.2"

Example usage

static SOMETHING: LateInit<String> = LateInit::new();

fn main() {
    let environment_value = std::env::var("ENV_VALUE").unwrap();
    unsafe { SOMETHING.init(environment_value); }

    println!("{}", SOMETHING);
}

Design

The LateInit type provides an unsafe interface for initializing static variables at runtime. Design goals for this crate are to provide checked, one-time initialization and unchecked, zero-cost access thereafter. The intention is to obviate the need for static mut in situations where only a single mutation is required for initialization purposes.

Methods like is_initialized, init_once, or similar are not and will not be supported because of the narrow scope of these design goals. If you need to check whether a LateInit is initialized, you're using it incorrectly.

This crate should be used sparingly and carefully—it breaks safety because access is really unsafe despite not being marked as such, since lateinit provides no guarantees about whether a value is initialized before it is used. It's on you (the programmer) to maintain this invariant. Bad things™ will happen if you don't. It's heavily suggested that you initialize only in a clearly demarcated region of setup code.

Features

#[no_std] is supported.

There are debug_asserts in trait implementations (most relevantly in Deref) to catch errors while testing. If you have performance concerns, you can turn off the debug_asserts with the debug_unchecked feature flag.

No runtime deps

Features