3 个版本
0.1.2 | 2024 年 8 月 6 日 |
---|---|
0.1.1 | 2024 年 8 月 6 日 |
0.1.0 | 2024 年 8 月 5 日 |
#2450 in Rust 模式
每月 325 次下载
7KB
102 行
Offer Cell
一个 Rust 库,用于定义一种模式,提供对存储数据的引用,并可选地转移该数据的所有权。
使用方法
初始化
// a cell may be created
let cell = OfferCell::new(42);
// or initialzed as empty
let empty = OfferCell::empty();
访问数据
// access the item as a reference
match cell.item() {
Some(value) = (), // do something with the value
None => (), // returns none if there is no item
}
// access the item as a mutable reference
match cell.item_mut() {
Some(value) = (), // do something with the value
None => (), // returns none if there is no item
}
提供数据
此库的独特之处在于单元内的数据可以被 "提供"
// if the cell contains an item, it can be offered
let offered = cell.offer() {
Some(offered) => offered,
None => return,
};
// the offered item implements Deref and DerefMut
assert_eq!(offered.deref(), &42);
// if nothing else is done with the offered item,
// the data will stay in the cell for later
// alternatively the offering can be consumed
// this leaves nothing in the cell, and takes ownership of the data
let data = offered.take();