matklad / once_cell

Rust library for single assignment cells and lazy statics without macros

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

jRimbault opened this issue · comments

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 ?

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.

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?