3 个不稳定版本
| 0.1.1 | 2022年7月14日 | 
|---|---|
| 0.1.0 | 2022年7月9日 | 
| 0.0.1 | 2022年7月9日 | 
#2428 在 Rust 模式 中
50,259 每月下载量
用于 sonnerie
9KB
64 行
LendingCell 是一个可变容器,允许您获取相同对象的拥有引用。当拥有引用被丢弃时,所有权将返回到原始容器。
与将 Rust 的 所有权 规则移动到运行时的 std::cell::Cell 相比,LendingCell 将 Rust 的 生命周期 规则移动到运行时。
LendingCell 的值在构造时存在,但您可以通过调用 LendingCell::to_borrowed 将其转换为 BorrowedCell<T>。在此 BorrowedCell 存在期间(即,直到它被丢弃),调用 LendingCell::try_get 将返回 None。此 BorrowedCell 对您的类型具有独占访问权限,就像您有一个直接拥有的 T 实例一样,因此只要 T 是 Send,它就是 Send。最后,当您丢弃 BorrowedCell 时,T 将返回到 LendingCell。
如果您在丢弃 BorrowedCell 之前丢弃 LendingCell,则 T 将在丢弃 BorrowedCell 时被丢弃。
Rust 的内存安全规则强制执行的约定,如单一可变引用规则,因此在编译时部分确保(您不能获取到 T 的两个可变引用),但也部分在运行时确保(在 BorrowedCell 活跃期间,LendingCell 表现得像包含 None 的 Option)。
示例
let mut lender = LendingCell::new("borrowed");
let borrowed = lender.to_borrowed();
assert!(lender.try_get().is_none()); // `lender` is empty because it was borrowed
assert_eq!(*borrowed, "borrowed"); // it's certain that `borrowed` is valid while in scope
drop(borrowed); // dropping `borrowed` returns its value to `lender`
assert!(lender.try_get().is_some());