How to implement a Clone trait for a struct with hashmap<String,struct>

I'm new to Rust,My question is like this piece of code

pub struct a {
impl Clone for a {
pub struct b {
      member : HashMap<a,String>
// I cannot use the move value of b beacuse b does not impl the Clone trait
impl Clone for b {
           pub fn clone(&self) -> Self {
                     b {
                          member : self.member.clone()

and it errors:

error[E0599]: the method `clone` exists for struct `HashMap<String, a>`, but its trait bounds were not satisfied
   --> src/
35  |     pub struct a {
    |     --------------- doesn't satisfy `a: Clone`
82  |                member:self.member.clone()
    |                                    ^^^^^ method cannot be called on `HashMap<String, a>` due to unsatisfied trait bounds
   ::: /home/caviar-x/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/collections/hash/
206 | pub struct HashMap<K, V, S = RandomState> {
    | ----------------------------------------- doesn't satisfy `HashMap<String, a>: Clone`
    = note: the following trait bounds were not satisfied:
            `a: Clone`
            which is required by `HashMap<String,a>: Clone

Is there any solution?
considered the real develop environment is really complex.I paste my source code here

Anyway,Thank you for you answering!

This should work fine. If a: Clone, then HashMap<String, a>: Clone is also true. You must be missing something else somewhere else. By the way, pub fn in a trait is a syntax error; you should just write fn clone.


  1. You should just #[derive(Clone)] instead of implementing it manually whenever you can.
  2. Types in Rust are CamelCase by convention. Don't call your structs a and b; those should be A and B.
1 Like

Well, When I use #[derive(Clone)]It reported

error[E0277]: the trait bound `a: Clone` is not satisfied
  --> src/
77 |         member: HashMap<String,a>
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected an implementor of trait `Clone`
   = note: required because of the requirements on the impl of `Clone` for `HashMap<String, a>`
   = note: required by `clone`
   = note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)

reply for asides:2 : It is just a example not the real code XD

You have to implement Clone for the a type. Your example code from the question has this implementation, but the code that causes the error you're having does not have it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.