3个版本
使用旧的Rust 2015
0.1.2 | 2018年7月17日 |
---|---|
0.1.1 | 2018年7月16日 |
0.1.0 | 2018年7月16日 |
#1754 在 数据结构
17KB
210 行
take-some
一个简单的库,提供从各种集合中获取一些值的方法。
有时人们只是需要从集合中“获取”一个元素,不管它是哪一个。如果你是这种人,请随意使用这个旨在使你的(是的,是你的!)生活变得稍微轻松一点的crate。
现在让我们看看它是如何工作的。假设你想要实现一个哈希表,它由Rust的类型系统静态保证在任何时候都不为空。这样做最直接的方法是将它声明为一个项和其余项的配对,如下所示:struct NonEmptyHashMap<K, V, S> (((K, V), ::std::collections::HashMap<K, V,S>))
。
到目前为止,一切顺利。你显然想要为它创建一些漂亮的用户API,这包括从标准库中的正常HashMap
创建你的类型的实例。这时,take-some
crate就派上用场了!
extern crate take_some;
use std::collections::HashMap;
use std::hash::{BuildHasher, Hash};
use take_some::TakeSome;
struct NonEmptyHashMap<K, V, S> {
first: (K, V),
rest: HashMap<K, V, S>,
}
impl<K, V, S> NonEmptyHashMap<K, V, S>
where
K: Eq + Hash,
S: BuildHasher,
{
fn from_std_hashmap(mut map: HashMap<K, V, S>) -> Option<Self> {
map.take_some()
.map(|first| NonEmptyHashMap { first, rest: map })
}
// An alternative implementation that takes advantage of the `TakeSome::split_at_some`
// method.
fn from_std_hashmap2(map: HashMap<K, V, S>) -> Option<Self> {
map.split_at_some()
.map(|(first, rest)| NonEmptyHashMap { first, rest })
.ok()
}
}
fn main() {
let map: HashMap<String, String> = vec![
("first".into(), "lol".into()),
("second".into(), "lul".into()),
].into_iter()
.collect();
let non_empty_map = NonEmptyHashMap::from_std_hashmap(map);
assert!(non_empty_map.is_some());
let empty_map: HashMap<String, String> = HashMap::new();
let non_empty_map = NonEmptyHashMap::from_std_hashmap(empty_map);
// It is entirely impossible (hail to the type system!) to create an instance of the
// `NonEmptyHashMap` with an empty map!
assert!(non_empty_map.is_none());
}
就是这样!是的,就这么简单。
如果你想为你的自定义集合实现trait,请查看crate的源代码(btree_map.rs、
hash_set.rs、
vec.rs等),或者查看
examples
目录中的一个示例,我们在其中为“外部”类型实现了trait。
许可证:MIT/Apache-2.0