| 1 |
//! Demonstrate various forms of `#[ctor]` statics. |
| 2 |
use std::mem::MaybeUninit; |
| 3 |
|
| 4 |
use ctor::ctor; |
| 5 |
|
| 6 |
#[derive(Debug)] |
| 7 |
#[allow(dead_code)] |
| 8 |
struct MyStatic(String); |
| 9 |
|
| 10 |
impl MyStatic { |
| 11 |
fn new(s: impl AsRef<str>) -> Self { |
| 12 |
Self(s.as_ref().to_string()) |
| 13 |
} |
| 14 |
} |
| 15 |
|
| 16 |
#[ctor(unsafe)] |
| 17 |
static STATIC_CTOR: MyStatic = MyStatic::new("foo"); |
| 18 |
|
| 19 |
#[ctor(unsafe)] |
| 20 |
static STATIC_CTOR_REF: &'static MyStatic = &MyStatic::new("foo"); |
| 21 |
|
| 22 |
/// This is not a recommended pattern - just demonstrating how to return static |
| 23 |
/// refs. |
| 24 |
#[ctor(unsafe)] |
| 25 |
#[allow(static_mut_refs)] |
| 26 |
static STATIC_CTOR_REF_GLOBAL: &'static MyStatic = { |
| 27 |
unsafe { |
| 28 |
static mut GLOBAL: MaybeUninit<MyStatic> = MaybeUninit::uninit(); |
| 29 |
|
| 30 |
GLOBAL.write(MyStatic::new("foo")); |
| 31 |
GLOBAL.assume_init_ref() |
| 32 |
} |
| 33 |
}; |
| 34 |
|
| 35 |
/// The above is a similar form to this: |
| 36 |
pub static FOO: &'static (dyn ::core::fmt::Debug + Sync) = &"foo"; |
| 37 |
|
| 38 |
fn main() { |
| 39 |
println!("STATIC_CTOR: {:?}", STATIC_CTOR); |
| 40 |
println!("STATIC_CTOR_REF: {:?}", STATIC_CTOR_REF); |
| 41 |
println!("STATIC_CTOR_REF_GLOBAL: {:?}", STATIC_CTOR_REF_GLOBAL); |
| 42 |
} |