Bounded Static
This crate defines the ToBoundedStatic
and IntoBoundedStatic traits,
the ToStatic macro and provides impls
for common types. This crate has zero-dependencies, is no_std friendly and
forbids unsafe code.
As described in the Common Rust Lifetime Misconceptions:
T: 'staticshould be read as "Tis bounded by a'staticlifetime" not "Thas a'staticlifetime".
The traits ToBoundedStatic and IntoBoundedStatic can be used to convert any suitable T and &T to an
owned T such that T: 'static. Both traits define an associated type which is bounded by 'static and provide a
method to convert to that bounded type.
The macros ToStatic can be used to automatically derive ToBoundedStatic and IntoBoundedStatic for any struct
or enum that can be converted to a form that is bounded by 'static.
Refer to the crate documentation for details and examples.
FAQ
When is this useful?
This is useful for data structures which directly or indirectly contain Cow<T> types that must be supplied to
a function which requires the 'static bound (i.e. std::thread::spawn):
How does this differ from the ToOwned trait?
The ToOwned trait defines an associated type Owned which
is not bound by 'static and therefore the follow will not compile:
use Cow;
Results in the following error:
error[E0597]: `s` does not live long enough
--> src/lib.rs:12:36
|
12 | let foo = Foo { foo: Cow::from(&s) };
| ----------^^-
| | |
| | borrowed value does not live long enough
| argument requires that `s` is borrowed for `'static`
13 | ensure_static(foo.to_owned())
14 | }
| - `s` dropped here while still borrowed
Replacing Clone with ToStatic and using into_static() (or to_static() as needed) allows the example to compile:
use Cow;
License
bounded-static is distributed under the terms of the Apache License (Version 2.0).
See LICENSE for details.
Copyright 2022