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.
Two possible answers:
The method is called clone with a lower-case c. Rust is a case-sensitive language.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With