Crates.io | static_cell |
lib.rs | static_cell |
version | 2.1.0 |
source | src |
created_at | 2022-08-21 19:56:46.124924 |
updated_at | 2024-04-26 20:50:21.754106 |
description | Statically allocated, initialized at runtime cell. |
homepage | |
repository | https://github.com/embassy-rs/static-cell |
max_upload_size | |
id | 649930 |
size | 27,231 |
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:
&'static T
, but T
can't be constructed in const context so you can't simply use a static
.&'static mut T
, not just &'static T
.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);
alloc
, you can use Box::leak()
.unsafe
, you can use static mut THING: MaybeUninit<T>
.&'static T
(instead of &'static mut T
), there's OnceCell
(not thread-safe though) or OnceLock
(thread-safe, but requires std
).This crate uses portable-atomic
, so on targets without native
atomics you must import a crate that provides a critical-section
implementation. See the critical-section
README for details.
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.
This work is licensed under either of
at your option.
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.