如何在Rust中写出支持右手是复杂情况下的引用的+=操作的特质约束 [重复]。

问题描述 投票:0回答:1

我想写一个支持Add操作的Vector结构,并写一些使用Vector结构的trait,所以我写了这个。

use std::ops::*;
#[derive(Clone)]
struct Vector<T>(Vec<T>);

impl<'a, T> Add<&'a Vector<T>> for Vector<T>
where
    T: AddAssign<&'a T>,
{
    type Output = Vector<T>;
    fn add(mut self, rhs: &'a Vector<T>) -> Self::Output {
        self.0
            .iter_mut()
            .zip(rhs.0.iter())
            .for_each(|(left, right)| {
                *left += right;
            });
        self
    }
}

trait SomeOperation<'a ,T>
where
    T: AddAssign<&'a T>+Clone + 'a,
{
    fn add(u:Vector<T>,v:&'a Vector<T>)->Vector<T>{
        let w = u+v;
        let x = v.clone()+&w;
        x
    }
}

但是出现了编译错误。

21 | trait SomeOperation<'a ,T>
   |                     -- lifetime `'a` defined here
...
27 |         let x = v.clone()+&w;
   |                           ^^
   |                           |
   |                           borrowed value does not live long enough
   |                           requires that `w` is borrowed for `'a`
28 |         x
29 |     }
   |     - `w` dropped here while still borrowed

怎样才能避免这类错误的发生。

rust overloading traits operator-keyword
1个回答
0
投票

你说要实施 AddAssign 但你的代码试图实现 Add. 还有,我不知道什么是 SomeOperation 是为了。 我加了 Debug 特质到派生线。

use std::ops::*;
#[derive(Clone, Debug)]
struct Vector<T>(Vec<T>);

impl<'a, T> AddAssign<&'a Vector<T>> for Vector<T>
where
    T: AddAssign<&'a T>
{
    fn add_assign(&mut self, rhs: &'a Vector<T>) {
        self.0
            .iter_mut()
            .zip(rhs.0.iter())
            .for_each(|(left, right)| {
                *left += right;
            });
    }
}
impl<'a, 'b, T> Add<& 'b Vector<T>> for & 'a Vector<T>
where
    Vector<T>: AddAssign<& 'b Vector<T>>,
    T: Clone,
{
    type Output = Vector<T>;
    fn add(self, other: & 'b Vector<T>) -> Self::Output {
        let mut res: Vector<T> = self.clone();
        res += other;
        res
    }
}

fn main() {
    let mut v1: Vector<u32> = Vector(vec![1, 2, 3]);
    let v2 = Vector(vec![4, 5, 6]);
    println!("Add:     {:?}", &v1 + &v2);
    v1 += &v2;
    println!("AddAssign{:?}", v1);
}
© www.soinside.com 2019 - 2024. All rights reserved.