Access to struct field inside trait method


#1

How can I rethink/rewrite something as simple as this?

use std::ops::{Add, Sub, Mul, Div};

pub struct A<T> {
    x: T
}

impl<T> A<T> where T: Mul<T, Output = T> {
    pub fn get_square(&self) -> T { self.x * self.x }
}

<anon>:8:37: 8:41 error: cannot move out of borrowed content
<anon>:8     pub fn get_square(&self) -> T { self.x * self.x }
                                             ^~~~
<anon>:8:46: 8:50 error: cannot move out of borrowed content
<anon>:8     pub fn get_square(&self) -> T { self.x * self.x }
                                                      ^~~~
error: aborting due to 2 previous errors
playpen: application terminated with error code 101

I really don’t get it, what’s the correct way to operate on struct fields through traits to compute another struct field?
I’ve seen that the problem has to do with the generic type T, but how can I make struct A generic on T?


#2

The code snippet doesn’t seem to match the question. The problem with the code is that Mul::mul consumes the operands (it is usually implemented for Copy types after all). With a Copy bound the example works

impl<T> A<T> where T: Mul<T, Output = T> + Copy {
    pub fn get_square(&self) -> T { self.x * self.x }
}

fn main() {
    let x = A { x: 2 };
    println!("{}", x.get_square());
}

#3

Thank you very much, I’m not familiar with some traits or terminology yet, coming from C/C++ world, things seem weird til I learn from errors…