【问题标题】:How to impl add for a generic in Rust如何在 Rust 中为泛型实现添加
【发布时间】:2021-04-25 02:05:16
【问题描述】:

为什么编译器不知道如何添加 &Point ? 收到以下错误: 错误[E0369]:无法将&Point<TextP> 添加到&Point<TextP> --> src/main.rs:72:16 | 72 |让 g = &e + &f; | -- ^ -- &点 | | | &观点 | = 注意:&Point<TextP> 可能缺少std::ops::Add 的实现



use std::ops::Add;
use std::cmp::PartialEq;

#[derive(Debug)]
pub struct Point<T> {
    x:Option<T>,
    y:T,
}

#[derive(Debug)]
pub struct TextP {
    p: i32
}

impl Add for TextP {
    type Output = TextP;
    fn add(self, other: TextP) -> TextP {
        TextP{p: self.p + other.p}
    }
}

impl <'a, 'b> Add<&'b TextP> for &'a TextP {
    type Output = TextP;
    fn add(self, other: &'b TextP) -> TextP {
        TextP {p: self.p + other.p}
    }
} 


impl<'a, 'b, T> Add<&'b Point<T>> for &'a Point<T> 
    where &'a T: Add<&'b T, Output=T>, 
      T: PartialEq + Add<Output = T>
{
    type Output = Point<T>;
    fn add(self, other: &'b Point<T>) -> Point<T> {
        Point {
            x: Some(self.x.as_ref().unwrap() + other.x.as_ref().unwrap()),
            y: self.y + other.y
        }
    }
}




impl<T: Add<Output = T>> Add for Point<T> {
    type Output = Point<T>;
    fn add(self, other: Point<T>) -> Point<T> {
        Point {
            x:Some(self.x.unwrap() + other.x.unwrap()),
            y:self.y + other.y,
        }
    }
}



fn main() {
    let a = Point{x:Some(5.5), y:5.5};
    let b = Point{x:Some(30.5), y:50.6};
    let c = &a + &b;
    println!("{:?}", a);
    let d = a + b;
    println!("c = {:?}",c);
    println!("d = {:?}",d);

    let e = Point{x:Some(TextP{p:1}), y:TextP{p:2}};
    let f = Point{x:Some(TextP{p:1}), y:TextP{p:2}};
    let g = &e + &f;
    println!("{:?}", g);

    let x = TextP {p: 1};
    let y = TextP {p: 1};
    let z = &x + &y;
}

【问题讨论】:

    标签: rust


    【解决方案1】:

    您要求T 在您的Add 实例中为PartialEq,即使您没有为PartialEq 提供TextP,也不需要它。只需删除无关的约束即可。

    impl<'a, 'b, T> Add<&'b Point<T>> for &'a Point<T> 
    where &'a T: Add<&'b T, Output=T> {
      ...
    }
    

    接下来,您对 Point 值中的 T 值没有所有权(因为您只借用了 Point 本身),所以您所能做的就是添加引用,而不是值。

    impl<'a, 'b, T> Add<&'b Point<T>> for &'a Point<T> 
    where &'a T: Add<&'b T, Output=T> {
        type Output = Point<T>;
        fn add(self, other: &'b Point<T>) -> Point<T> {
            Point {
                x: Some(self.x.as_ref().unwrap() + other.x.as_ref().unwrap()),
                y: &self.y + &other.y
            }
        }
    }
    

    【讨论】:

    • 是的。谢谢。想知道为什么编译器无法标记您对尝试获取点内值的所有权的观察。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多