Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

README std::cell::OnceLock usage example #1034

Closed
nyurik opened this issue Jul 11, 2023 · 3 comments
Closed

README std::cell::OnceLock usage example #1034

nyurik opened this issue Jul 11, 2023 · 3 comments

Comments

@nyurik
Copy link

nyurik commented Jul 11, 2023

Rust v1.70 introduced a new std::cell::OnceCell primitive that should (in theory) replace the commonly used once_cell crate.

Regex README documents how to use the once_cell crate. Should it be updated with the now standardized OnceCell?

@BurntSushi
Copy link
Member

I think you mean std::sync::OnceLock.

OnceLock is a slightly lower level primitive and is a little more annoying to use. It's also very new. I'd rather stick with once_cell for now. I do expect I'll update this at some point.

@BurntSushi BurntSushi closed this as not planned Won't fix, can't repro, duplicate, stale Jul 11, 2023
@nyurik
Copy link
Author

nyurik commented Jul 11, 2023

Sure, and thx, you are right - I meant OnceLock. Just in case someone would like to use the Readme example with OnceLock, posting bellow. Could you clarify what you meant by a bit lower level - it seems the usage is nearly identical?

use regex::Regex;
use std::sync::OnceLock;

fn some_helper_function(haystack: &str) -> bool {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"...").unwrap())
        .is_match(haystack)
}

fn main() {
    assert!(some_helper_function("abc"));
    assert!(!some_helper_function("ac"));
}

@nyurik nyurik changed the title README std::cell::OnceCell usage example README std::cell::OnceLock usage example Jul 11, 2023
@BurntSushi
Copy link
Member

Compare static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"...").unwrap()); with what you have, which is two lines. It's a small thing, but the Lazy<Regex> approach is definitely a little nicer.

The once_cell crate docs do have a regex! macro that uses OnceCell and its use is pretty nice:

macro_rules! regex {
    ($re:literal $(,)?) => {{
        static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new();
        RE.get_or_init(|| regex::Regex::new($re).unwrap())
    }};
}

There is some more discussion about that in #709.

I overall don't think it's a huge problem to leave it as-is. I'm sure it will get migrated eventually, but I prefer to move more slowly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants