Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specified generic type to implement Clone but type doesn't have Clone method

Tags:

rust

I have code like this, where I need to insert something into two separate hashmaps. I only want generic types that implement Clone.

use std::collections::HashMap;
use std::clone::Clone;

pub struct Something<A, B> {
    hm1: HashMap<usize, B>,
    hm2: HashMap<usize, B>,
    other: A,
}

impl<A, B> Something<A, B>
    where B: Clone
{
    fn add_to_both_hm(&mut self, x: usize, y: usize, weight: B) {
        self.hm1.insert(x, weight.Clone());
        self.hm2.insert(y, weight);
    }
}

But when compiling, the compiler complains that error: no method named 'Clone' found for type 'B' in the current scope.

Why does it still error even though I specified where B: Clone? How can I fix that?

The rust playground is here.

like image 854
Julien Chien Avatar asked Oct 30 '25 18:10

Julien Chien


1 Answers

Two possible answers:

  1. The method is called clone with a lower-case c. Rust is a case-sensitive language.

  2. Clone is not a method, it's a trait. The name of a trait doesn't have anything to do with the name(s) of any methods it might define. In Clone's case, it defines a method clone for implementing types.

The solution in both cases is simple: write weight.clone() instead.

like image 135
DK. Avatar answered Nov 02 '25 09:11

DK.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!