轮询一系列事件时,需要丢弃重复项。
事件可以使用 序列化为字节.as_bytes(),然后可以将其放入缓存中以便可以跳过它们:
let mut cache = LruCache::new(10_000);
loop {
let events: Vec<Evt> = get_events().
.into_iter()
.filter_map(|evt| {
let key = evt.as_bytes().to_owned();
if cache.contains(&key) {
return None;
}
cache.put(key);
Some(Event::from_bytes(&evt.as_bytes()).unwrap())
})
.collect();
// ... use `events`
}
Run Code Online (Sandbox Code Playgroud)
在闭包中,我们需要将move事件从其中取出,以便它们的生命周期与事件一样长cache。
一种方法是拜访.to_owned()他们。然而,对于 [u8] 值,这被实现为 a .to_vec(),它复制它们而不是移动它们,从而产生额外的开销。
显然[T]切片实现了一个.into_vec()方法,但这在&[u8]引用中不可用:
error[E0599]: no method named `into_vec` found for reference `&[u8]` in the current scope
--> src/main.rs:55:41
|
55 | let key = evt.as_bytes().into_vec();
| ^^^^^^^^^^ help: there is an associated function with a similar name: `to_vec`
Run Code Online (Sandbox Code Playgroud)
如何&[u8]在不产生与复制相关的额外开销的情况下移出闭包?