generate_singleton

Attribute Macro generate_singleton 

Source
#[generate_singleton]
Expand description

Generate singleton static variable

  • generated variable name will be SCREAMING_CAMEL_CASE of InputName
  • InputName must be written in PascalCase
  • #[generate_singleton] will generate std::sync::OnceLock<InputType>
  • #[generate_singleton(expr) will generate std::sync::LazyLock<InputType>
  • expr type must be InputType

ยงExamples

use patternize::singleton::generate_singleton;

#[derive(Debug, PartialEq)]
#[generate_singleton]
struct SampleSingleton {
    data: std::string::String
}

#[derive(Debug, PartialEq)]
#[generate_singleton(SampleSingleton2 { data: "sample".to_string() })]
struct SampleSingleton2 {
    data: std::string::String
}

fn main(){
    // SAMPLE_SINGLETON: std::sync::OnceLock<SampleSingleton>
    SAMPLE_SINGLETON.set(SampleSingleton {data: "sample".to_string()});
     
    assert_eq!(SAMPLE_SINGLETON.get(), Some(&SampleSingleton { data: "sample".to_string() }));

    // SAMPLE_SINGLETON2: std::sync::LazyLock<SampleSingleton2>

    assert_eq!(&*SAMPLE_SINGLETON2, &SampleSingleton2 { data: "sample".to_string() });
}