【发布时间】: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