Expand description
§scoped_static
Lift references into
'staticsafely — at runtime.
scoped_static allows temporarily extending a reference’s lifetime to 'static using runtime safety checks.
This enables you to safely spawn asynchronous tasks, threads, or other 'static contexts without running into borrow checker limitations — while still avoiding undefined behavior.
§Motivation
Rust’s lifetime system ensures safety at compile time, but sometimes you need to move a non-'static reference into an async task or thread:
ⓘ
#[tokio::main]
async fn main() {
let concrete_value = Box::new(1.0);
let ref_value = &concrete_value; // This is does not live long enough (not 'static)
tokio::spawn(async move {
let value = **ref_value + 1.0;
assert_eq!(value, 2.0);
})
.await
.unwrap();
}This fails because the reference to ref_value isn’t 'static.
scoped_static solves this by allowing you to lift a reference to 'static under the protection of a scope guard that enforces correct drop order at runtime.
§Example
use scoped_static::{scoped, ScopedGuard};
#[tokio::main]
async fn main() {
let value = Box::new(1.0);
let ref_value = &value;
// `guard` ensures no derived "lifted" values exist when dropped.
// The type is `&mut ScopedGuard<'_, Box<f64>>`
let guard = scoped!(ref_value);
// `lifted` holds a `'static` reference to `'ref_value`
// The type is `Scoped<Box<f64>>`
let lifted = guard.lift();
tokio::spawn(async move {
// `lifted` moved here
let value = **lifted + 1.0;
assert_eq!(value, 2.0);
// `lifted` dropped
})
.await
.unwrap();
// Forgetting has no effect since `guard` is a reference
std::mem::forget(guard); // SAFE
// `guard` dropped
}See ScopedGuard and ScopedPinGuard for more info.
Macros§
- scoped
- A safe way to create a
ScopedGuard. - scoped_
pin - A safe way to create a
ScopedPinGuard.
Structs§
- Scoped
- A reference derived from a
ScopedGuard. The lifetime of the underlying value has been lifted to'static. SeeScopedGuardfor more info. - Scoped
Guard - A reference with lifetime
'athat can be lifted to a reference with a'staticlifetime (Scoped). Runtime checks are used to ensure that no derivedScopedexists when thisScopedGuardis dropped. - Scoped
Pin - A reference derived from a
ScopedPinGuard. The lifetime of the underlying value has been lifted to'static. SeeScopedPinGuardfor more info. - Scoped
PinGuard - A reference with lifetime
'athat can be lifted to a reference with a'staticlifetime (ScopedPin). Runtime checks are used to ensure that no derivedScopedPinexists when thisScopedPinGuardis dropped.