7 releases (stable)

2.0.0 Nov 2, 2023
1.3.0 Nov 2, 2023
1.2.0 Jul 3, 2023
1.1.0 May 31, 2023
0.0.0 Aug 21, 2022

#132 in Rust patterns

Download history 2667/week @ 2023-12-04 2794/week @ 2023-12-11 2604/week @ 2023-12-18 746/week @ 2023-12-25 1504/week @ 2024-01-01 1970/week @ 2024-01-08 1943/week @ 2024-01-15 2651/week @ 2024-01-22 2466/week @ 2024-01-29 1955/week @ 2024-02-05 2564/week @ 2024-02-12 3491/week @ 2024-02-19 3014/week @ 2024-02-26 3457/week @ 2024-03-04 4431/week @ 2024-03-11 4303/week @ 2024-03-18

15,338 downloads per month
Used in 29 crates (21 directly)

MIT/Apache

11KB
77 lines

static-cell

crates.io crates.io Documentation

Statically allocated, initialized at runtime cell.

StaticCell provides a no-std-compatible, no-alloc way to reserve memory at compile time for a value, but initialize it at runtime, and get a 'static reference to it.

This is useful in the following scenarios:

  • You need &'static T, but T can't be constructed in const context so you can't simply use a static.
  • You need &'static mut T, not just &'static T.

Example

use static_cell::StaticCell;

// Statically allocate memory for a `u32`.
static SOME_INT: StaticCell<u32> = StaticCell::new();

// Initialize it at runtime. This returns a `&'static mut`.
let x: &'static mut u32 = SOME_INT.init(42);
assert_eq!(*x, 42);

// Trying to call `.init()` again would panic, because the StaticCell is already initialized.
// SOME_INT.init(42);

Alternatives

  • If you can use alloc, you can use Box::leak().
  • If you're OK with unsafe, you can use static mut THING: MaybeUninit<T>.
  • If you need just &'static T (instead of &'static mut T), there's OnceCell (not thread-safe though) or OnceLock (thread-safe, but requires std).

Interoperability

This crate uses atomic-polyfill, so on targets without native atomics you must import a crate that provides a critical-section implementation. See the critical-section README for details.

Minimum Supported Rust Version (MSRV)

This crate is guaranteed to compile on stable Rust 1.56 and up. It might compile with older versions but that may change in any new patch release.

License

This work is licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~1MB
~15K SLoC