Const for LazyLock/OnceLock should Raise a error or warning

rustc version is : rustc 1.88.0

const WEB_SERVER2;
const WEB_SERVER;
can't pass the test;
but const change to static can pass test.

use std::sync::Arc;
use std::sync::LazyLock;
const WEB_SERVER2: LazyLock<Arc> = LazyLock::new(|| {
let web = start_web_server(&ResourceWebServerCfg {
host: "localhost".to_string(),
port: 0,
});
Arc::new(web)
});

fn get_web_server2() -> Arc {
(*WEB_SERVER2).clone()
}

#[test]
fn test_once_lock_for_start_server2() {
let w1 = get_web_server2();
let w2 = get_web_server2();
assert_eq!(w1.url, w2.url);
}

use std::sync::OnceLock;

const WEB_SERVER: OnceLock<Arc> = OnceLock::new();

fn get_web_server() -> Arc {
WEB_SERVER
.get_or_init(|| {
let web = start_web_server(&ResourceWebServerCfg {
host: "localhost".to_string(),
port: 8080,
});
Arc::new(web)
})
.clone()
}

#[test]
fn test_once_lock_for_start_server() {
let w1 = get_web_server();
let w2 = get_web_server();
assert_eq!(w1.url, w2.url);
}

Please edit the post to use formatting to make it more readable.

https://users.rust-lang.org/t/forum-code-formatting-and-syntax-highlighting/42214

https://meta.discourse.org/t/supported-formatting-in-posts-markdown-bbcode-and-html/239348

2 Likes

There is a clippy lint for this problem: https://rust-lang.github.io/rust-clippy/master/index.html#declare_interior_mutable_const

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.