如何克隆包含装箱特征对象的 HashMap? [英] How do I clone a HashMap containing a boxed trait object?

查看:37
本文介绍了如何克隆包含装箱特征对象的 HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有自定义哈希器的 HashMap.这个 HashMap 的项目没有实现 trait Clone(这是一个 trait),但是有克隆这样的项目的功能:

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();
}

我如何快速(在代码中)和有效地(不创建临时集合)克隆 hash_map?

How I could clone hash_map shortly (in code) and efficiently (without creating a temporary collection)?

推荐答案

您可以为装箱的 trait 对象本身实现 Clone :

You can implement Clone for the boxed trait object itself:

impl Clone for Box<Item> {
    fn clone(&self) -> Self {
        self.cloned()
    }
}

现在您可以克隆HashMap.请注意,自定义哈希器与问题无关.

Now you may clone the HashMap. Note that the custom hasher has nothing to do with the problem.

另见

这篇关于如何克隆包含装箱特征对象的 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆