首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >返回两个泛型相加的结果时类型不匹配

返回两个泛型相加的结果时类型不匹配
EN

Stack Overflow用户
提问于 2016-06-06 06:04:57
回答 3查看 861关注 0票数 6

我正在学习Rust,已经阅读了Rust主页,并且正在尝试一些小的示例程序。下面是失败的代码:

代码语言:javascript
复制
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}
    }
}

以下是错误消息:

代码语言:javascript
复制
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}
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我不明白为什么它不能编译。

EN

回答 3

Stack Overflow用户

发布于 2016-06-06 06:26:02

Add trait被定义为

代码语言:javascript
复制
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)相同。但是,对于输出类型必须是什么没有限制。

有两种可能的解决方案:

  1. 说您将返回一个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,} }

另请参阅:

票数 6
EN

Stack Overflow用户

发布于 2016-06-06 06:23:02

您的add实现会生成一个Complex<<T as core::ops::Add>::Output><T as core::ops::Add>::Output (即用于TAdd<T>实现的Output )不能保证与T相同。您可以在Output关联类型上添加约束,以将您的实现限制为仅当它们实际上相同时才可用:

代码语言:javascript
复制
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>,则可以通过添加TU来使实现尽可能通用。

代码语言:javascript
复制
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 }
    }
}
票数 4
EN

Stack Overflow用户

发布于 2016-06-06 06:16:49

您需要为T指定Add的输出类型

代码语言:javascript
复制
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}
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37647248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档