Home > Net >  How to implement generics struct correctly
How to implement generics struct correctly

Time:09-28

I am new to Rust, and try to implement Rectangle generic type. The following code gives compile error "move occurs because self.w has type T, which does not implement the Copy trait". How can I fix this and is there a better way to do it?

struct Rectangle <T>{
    w : T,
    h : T 
}

impl<T:std::ops::Mul   std::ops::MulAssign   std::ops::Mul<Output = T>> Rectangle<T>{
    fn get_area(&self) -> T{
        return self.w * self.h;
    }

    fn scale(&mut self, scale:T) {
        self.w *= scale;
        self.h *= scale;
    }

    fn new(w:T, h:T) -> Rectangle<T> {
        return Rectangle{
            w:w,
            h:h
        };
    }
}

fn main() {
    let rect = Rectangle::new(1.2, 3.4);
    let area = rect.get_area();
    println!("Rectangle Area {area}");
}

CodePudding user response:

Your problem is that you need to add Copy to the list of traits you want T to implement:

impl <T: ...   Copy> Rectangle {
             ^^^^^^

But I find keeping track of those long traits for numeric types to be painful, and so I usually introduce an umbrella trait. In your case it would look something like:

trait Field: std::ops::Mul   std::ops::MulAssign   std::ops::Mul<Output = Self>   Copy {}
impl <T:std::ops::Mul   std::ops::MulAssign   std::ops::Mul<Output = Self>   Copy> Field for T {}

Then you can just write:

impl <T:Field> Rectangle {
 ...
}
  • Related