9 个版本 (破坏性)
| 0.8.0 | 2024年6月23日 |
|---|---|
| 0.7.0 | 2023年10月25日 |
| 0.6.0 | 2023年10月20日 |
| 0.5.0 | 2023年4月29日 |
| 0.1.0 | 2022年2月18日 |
#160 在 Rust 模式
每月下载 10,612 次
在 21 个 仓库中使用 21 (直接使用 7 个)
62KB
1.5K SLoC
有界静态
此软件包定义了 ToBoundedStatic 和 IntoBoundedStatic 特性,ToStatic 宏,并提供常见类型的实现。此软件包无依赖项,对 no_std 友好,并禁止使用 unsafe 代码。
如 常见的 Rust 生命周期误解 中所述
T: 'static应读作 "T由'static生命周期限制",而不是 "T有一个'static生命周期"。
可以使用特性 ToBoundedStatic 和 IntoBoundedStatic 将任何合适的 T 和 &T 转换为受 'static 限制的所有权 T。这两个特性定义了一个受 'static 限制的关联类型,并提供了一个将其转换为该限制类型的方法。
可以使用宏 ToStatic 自动为任何可以转换为受 'static 限制形式的 struct 或 enum 推导 ToBoundedStatic 和 IntoBoundedStatic。
有关详细信息和方法示例,请参阅软件包 文档。
常见问题解答
何时使用此功能?
这对于包含必须提供给需要 'static 绑定的函数(例如 std::thread::spawn)的 Cow<T> 类型的数据结构非常有用。
#[derive(Debug, PartialEq, ToStatic)]
struct Foo<'a> {
foo: Cow<'a, str>,
bar: Vec<Bar<'a>>
}
#[derive(Debug, PartialEq, ToStatic)]
enum Bar<'a> {
First,
Second(Cow<'a, str>),
}
fn main() {
let value = String::from("data");
let foo = Foo {
foo: Cow::from(&value),
bar: vec![Bar::First, Bar::Second(Cow::from(&value))]
};
let foo_static = foo.into_static();
std::thread::spawn(move || {
assert_eq!(foo_static.foo, "data");
assert_eq!(foo_static.bar, vec![Bar::First, Bar::Second("data".into())])
}).join().unwrap();
}
这与 ToOwned 特性有何不同?
ToOwned 特性定义了一个关联类型 Owned,它不受 'static 绑定,因此以下代码将无法编译
use std::borrow::Cow;
fn main() {
#[derive(Clone)]
struct Foo<'a> {
foo: Cow<'a, str>,
}
fn ensure_static<T: 'static>(_: T) {}
let s = String::from("data");
let foo = Foo { foo: Cow::from(&s) };
ensure_static(foo.to_owned())
}
导致以下错误
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
将 Clone 替换为 ToStatic 并使用 into_static()(或根据需要使用 to_static())可以使示例编译通过
use std::borrow::Cow;
fn main() {
#[derive(ToStatic)]
struct Foo<'a> {
foo: Cow<'a, str>,
}
fn ensure_static<T: 'static>(_: T) {}
let s = String::from("data");
let foo = Foo { foo: Cow::from(&s) };
ensure_static(foo.into_static())
}
许可
bounded-static 在 Apache 许可证(版本 2.0)的条款下分发。
有关详细信息,请参阅 LICENSE。
版权所有 2022
依赖关系
~0–5.5MB
~14K SLoC