LazyLock Delays Global Static Until First Use
Initialize process-wide state on first access with LazyLock: the constructor runs once, later reads borrow the same static, and no unsafe appears anywhere.
Code
use std::sync::LazyLock;
// 进程内只构造一次的静态数据:LazyLock 在首次访问时执行闭包
static RATE_LIMITS: LazyLock<[u32; 3]> = LazyLock::new(|| {
// 构造逻辑可以是任意复杂度(读文件、编译规则、建连接)
[60, 300, 3600]
});
fn main() {
// 两次访问拿到同一份静态数据的引用,闭包只运行一次
println!("window1: {:?}", *RATE_LIMITS);
println!("window2: {:?}", *RATE_LIMITS);
// Deref 到内层数组:像普通数组一样遍历与查询
let shortest = RATE_LIMITS.iter().min();
println!("shortest window: {:?}", shortest);
// 索引取出的 u32 借自静态数据,没有发生克隆
let first = RATE_LIMITS[0];
println!("first: {first}");
}How it works
Count the function main as the entire surface area of LazyLock Delays Global Static Until First Use.
Putting it to use
Running the file prints labeled results such as window1:, window2:, shortest window: — each operation’s effect is visible in the output.
Core lines
let shortest = RATE_LIMITS.iter().min();
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does LazyLock Delays Global Static Until First Use print when run?
- Running the file directly is enough — expect labeled output lines such as `window1:`, `window2:`, `shortest window:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.