3 个版本 (破坏性更新)
0.3.0 | 2023 年 10 月 20 日 |
---|---|
0.2.0 | 2023 年 10 月 16 日 |
0.1.0 | 2023 年 10 月 16 日 |
#2309 在 Rust 模式
在 vec_vec 中使用
11KB
106 行
Stack trait
具有 LIFO 元素 entry API 的 Stack trait。
示例
use stack_trait::{Stack, LIFOEntry};
// types are written explicitly for clarity
fn main() {
let mut stack: Vec<i32> = vec![1, 2, 3];
// When we push to the stack, we can get an "entry" object
// that corresponds to the pushed element.
let mut entry: LIFOEntry<'_, Vec<i32>> = stack.lifo_push(4);
// This object can be dereferenced to get the shared
// reference to the element.
assert_eq!(*entry, 4);
// We also can dereference LIFO entry mutably to get
// the mutable reference to the element and change the
// element.
*entry = 5;
// After this we can dereference it immutably again.
assert_eq!(*entry, 5);
// However, we must drop the entry before we can use
// the stack again.
drop(entry);
assert_eq!(stack, vec![1, 2, 3, 5]);
// In this case, we could be bold to use
// `.lifo_unchecked()` unsafe method but the
// boundary check at this unwrap should be
// optimized out by the compiler.
let entry = stack.lifo().unwrap();
// In addition, we can pop the element from the stack
assert_eq!(entry.pop_pointee(), 5);
assert_eq!(stack, vec![1, 2, 3]);
}
如上所示,LIFOEntry<'a,C>
可以根据我们的意愿转换为 &'a C
,&'a mut C
或甚至是 C
。
注意
在编写本文时,此 trait 仅实现了 Vec<T>
。然而,对于其他类型,如 ArrayVec<T>
的实现也受到欢迎。