小编Rus*_*ted的帖子

const 变量返回两个不同的值

今天我对 nightly 模块做了一些测试std::lazy它在局部变量中运行良好。然而,当我定义一个const变量时,它给了我两个不同的值。似乎 Colsure 被调用了多次。

#![feature(once_cell)]
use rand::Rng; // 0.8.4
use std::lazy::Lazy;

const CONST_LAZY: Lazy<i32> = Lazy::new(|| rand::thread_rng().gen::<i32>());

fn main() {
    let local_lazy: Lazy<i32> = Lazy::new(|| rand::thread_rng().gen::<i32>());
    println!("{}", *local_lazy); // -1475423855
    println!("{}", *local_lazy); // -1475423855

    println!("{}", *CONST_LAZY); // 1975106939
    println!("{}", *CONST_LAZY); // -1848043613
}
Run Code Online (Sandbox Code Playgroud)

rust

7
推荐指数
1
解决办法
274
查看次数

标签 统计

rust ×1