General math without copying in rust

I want to write some general mathematical functions without assuming that my types can be copied. This seems impossible, because mathematical operators consume values ​​instead of borrowing them. Therefore, you need to copy the object, just for simple math. I could just move them, but this is not possible in the borrowed context that I need when I want to mutate the structure.

Here is a simple example where there are problems:

use std::ops::Add;

struct NoCopy<T>(T); //some non-copyable struct, (maybe a vector)
struct Cont<T>(NoCopy<T>); //some struct contaioning a noncopyable struct

impl<T: Add<Output=T>> Add for NoCopy<T> {
    type Output = NoCopy<T>;
    fn add(self, x: NoCopy<T>) -> NoCopy<T> {
        NoCopy(self.0+x.0)
    }
}

fn main() {
    let x = NoCopy(1);
    let cont = Cont(x);
    let rel = NoCopy(2);
    cont.0=cont.0+rel; //addition makes struct cont invalid, so i have to copy
}

- (, ), , , , , " ". ? ( )?

+3
1

- Add :

impl<'a, T: Copy + Add<Output = T>> Add for &'a NoCopy<T> {
    type Output = NoCopy<T>;
    fn add(self, rhs: Self) -> NoCopy<T> {
        NoCopy(self.0+rhs.0)
    }
}

, Copy. . Copy T, (true ); T , .

, , :

fn main() {
    let x = NoCopy(1);
    let mut cont = Cont(x);
    let rel = NoCopy(2);
    cont.0=&cont.0+&rel;
}

( )

+9

Source: https://habr.com/ru/post/1694330/


All Articles