我正在学习Rust,已经阅读了Rust主页,并且正在尝试一些小的示例程序。下面是失败的代码:
use std::ops::Add;
pub struct Complex<T> {
pub re: T,
pub im: T,
}
impl <T: Add> Add<Complex<T>> for Complex<T> {
type Output = Complex<T>;
fn add(self, other: Complex<T>) -> Complex<T> {
Complex {re: self.re + other.re, im: self.im + other.im}
}
}以下是错误消息:
src/lib.rs:11:3: 11:59 error: mismatched types:
expected `Complex<T>`,
found `Complex<<T as core::ops::Add>::Output>`
(expected type parameter,
found associated type) [E0308]
src/lib.rs:11 Complex {re: self.re + other.re, im: self.im + other.im}
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~我不明白为什么它不能编译。
发布于 2016-06-06 06:26:02
Add trait被定义为
pub trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}也就是说,给定一个用于Self的类型(为其实现特征的类型)和一个用于右侧的类型(RHS,正在添加的内容),将会产生一个唯一的类型:Output。
从概念上讲,这允许您创建一个可以添加类型B的类型A,这将始终生成第三个类型C。
在您的示例中,您已经约束了T来实现Add。默认情况下,假定RHS类型与为其实现特征的类型(RHS = Self)相同。但是,对于输出类型必须是什么没有限制。
有两种可能的解决方案:
Complex,无论添加T的结果类型是什么,都已将其参数化:impl Add for Complex where T: Add,{ type Output = Complex;fn add(self,other: Complex) -> Complex { Complex { re: self.re + other.re,im: self.im + other.im,}
T限制为那些在与自身相加时返回相同类型的类型:复杂类型的impl Add where T: Add,{T>= Complex;fn add(self,other: Complex) -> Complex { Complex { re: self.re + other.re,im: self.im + other.im,} }
另请参阅:
发布于 2016-06-06 06:23:02
您的add实现会生成一个Complex<<T as core::ops::Add>::Output>。<T as core::ops::Add>::Output (即用于T的Add<T>实现的Output )不能保证与T相同。您可以在Output关联类型上添加约束,以将您的实现限制为仅当它们实际上相同时才可用:
impl<T: Add<Output = T>> Add for Complex<T> {
type Output = Complex<T>;
fn add(self, other: Complex<T>) -> Complex<T> {
Complex { re: self.re + other.re, im: self.im + other.im }
}
}或者,如果可以添加Complex<T>和Complex<U>,并且可以返回Complex<<T as Add<U>>::Output>,则可以通过添加T和U来使实现尽可能通用。
impl<T: Add<U>, U> Add<Complex<U>> for Complex<T> {
type Output = Complex<<T as Add<U>>::Output>;
fn add(self, other: Complex<U>) -> Self::Output {
Complex { re: self.re + other.re, im: self.im + other.im }
}
}发布于 2016-06-06 06:16:49
您需要为T指定Add的输出类型
impl <T: Add<Output = T>> Add for Complex<T> {
type Output = Complex<T>;
fn add(self, other: Complex<T>) -> Complex<T> {
Complex {re: self.re + other.re, im: self.im + other.im}
}
}https://stackoverflow.com/questions/37647248
复制相似问题