5个版本
0.2.1 | 2020年10月12日 |
---|---|
0.2.0 | 2020年8月20日 |
0.1.2 | 2020年7月12日 |
0.1.1 | 2020年7月10日 |
0.1.0 | 2020年7月10日 |
2035 在 数据结构 中
在 monster_maker_core 中使用
18KB
135 行
引用计数的可哈希包装器。
为 Rc<T>
和 Weak<T>
引用提供可哈希的包装器,分别使用 HashableRc<T>
和 HashableWeak<T>
类型。这允许在基于哈希的数据结构中,如 HashMap
或 HashSet
中使用强和弱引用计数。
快速入门
最常见的使用案例是将 Rc<T>
或 Weak<T>
包装到 HashableRc<T>
或 HashableWeak<T>
中,以便包含在基于哈希的容器中。以下是一个在 HashMap
中使用这两种类型作为键的示例。
use std::collections::HashMap;
use std::rc::{Rc, Weak};
use hashable_rc::{HashableRc, HashableWeak};
// Create a strong reference counting for an object.
let rc: Rc<u32> = Rc::new(42);
// Use the strong reference as a key for a HashMap.
let mut strong_map = HashMap::new();
strong_map.insert(HashableRc::new(rc.clone()), "foo");
assert_eq!(strong_map[&HashableRc::new(rc.clone())], "foo");
// Create a weak reference counting for the same object as above.
let weak: Weak<u32> = Rc::downgrade(&rc);
// Use the weak reference as a key for a HashMap.
let mut weak_map = HashMap::new();
weak_map.insert(HashableWeak::new(weak.clone()), "bar");
assert_eq!(weak_map[&HashableWeak::new(weak.clone())], "bar");
将它们插入其他基于哈希的容器(如 HashSet
)的方式类似。