dylanhart / ulid-rs

This is a Rust implementation of the ulid project

Home Page:https://crates.io/crates/ulid

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] Best way to embed a ULID as a constant?

Kleptine opened this issue · comments

I have a number of ULIDs in my code which are static. Currently I am just using a static function returning
Ulid::from_str("01FATR1B6ZNA09MEB7NH4DS49D")

Is there a recommended way to embed a ULID (ideally from the string form) as a constant?

Best way currently would be either using numeric constants (e.g. Ulid(12345)) or using something like the lazy_static crate. Eventually I'd like to refactor this crate to drop its use of lazy_static and to make everything const, but that hasn't happened yet.

Ulid::from_string() has been made const. The following is now valid on nightly (via #[feature(const_panic)]):

use ulid::Ulid;

macro_rules! ulid {
    ($str:expr) => {
        if let Ok(ulid) = ::ulid::Ulid::from_string($str) {
            ulid
        } else {
            panic!("Invalid Ulid literal")
        }
    }
}

const MY_ULID: Ulid = ulid!("01FATR1B6ZNA09MEB7NH4DS49D");

fn main() {
    println!("Hello, {}!", MY_ULID);
}

Wonderful, thanks!