matklad / once_cell

Rust library for single assignment cells and lazy statics without macros
Apache License 2.0
1.84k stars 110 forks source link

Add a warning in the FAQ about `const` vs `static` #145

Closed jRimbault closed 3 years ago

jRimbault commented 3 years ago

I think some people may have some misconceptions about what const and static actually means, this came up in this reddit thread today. I tried explaining shortly by analogy (I'm not the best explainer), the result of the constructor function is copy pasted everywhere the const result is used. Maybe this could warrant a reminder note in the FAQ part of the docs ?

matklad commented 3 years ago

cc https://github.com/rust-lang/rust/issues/40543

mrozekma commented 2 years ago

I just made this exact mistake (playground):

use once_cell::unsync::OnceCell; // 1.9.0

const CELL: OnceCell<bool> = OnceCell::new();

pub fn main() {
    assert_eq!(CELL.set(true), Ok(()));
    assert_eq!(CELL.set(true), Err(true)); // Fails
}

I assume based on the linked rust-lang conversation that there's no way for once_cell to catch this mistake and it would have to be a compiler change, but a warning in the FAQ might be worthwhile.

dsherret commented 1 year ago

I also just hit this. I wonder if perhaps there could be a debug panic if a lazy is initialized twice saying the user likley has it in a const by accident. Or maybe that’s not possible?