I have HashMap
with custom hasher. Items of this HashMap
without implemented trait Clone
(it's a trait), but there is function to clone items like this:
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use fnv::FnvHasher;
trait Item {
fn get_id(&self) -> i32;
fn cloned(&self) -> Box<Item>;
}
#[derive(Clone)]
struct ItemImpl {
id: i32,
foo: i32
}
impl Item for ItemImpl {
fn get_id(&self) -> i32 { self.id }
fn cloned(&self) -> Box<Item> { Box::new(self.clone()) }
}
fn main() {
let hash_map = HashMap::<i32, Box<Item>, BuildHasherDefault<FnvHasher>>::default();
}
How I could clone hash_map
shortly (in code) and efficiently (without creating a temporary collection)?
You can implement Clone
for the boxed trait object itself:
impl Clone for Box<Item> {
fn clone(&self) -> Self {
self.cloned()
}
}
Now you may clone the HashMap
. Note that the custom hasher has nothing to do with the problem.
See also
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.