使用具有泛型类型的运算符时出错 [英] Error when using operators with a generic type

查看:29
本文介绍了使用具有泛型类型的运算符时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Rust,我不明白为什么下面的代码会出错.

I'm learning rust and I can't understand why the following code gives an error.

use std::ops::Mul;
use std::ops::Add;

struct Vec2<T>
{
    x: T,
    y: T,
}

impl<T: Mul + Add> Vec2<T> {
    fn magnitude_squared(&self) -> T {
        self.x * self.x + self.y * self.y // error here
    }
}

fn main() {
    let x = Vec2 { x: 1f32, y: 1f32 };
    println!("{}", x.magnitude_squared());
}

错误消息(对我来说没有多大意义,除非两个浮点数相乘产生一些不可添加"类型):

Error message (doesn't make much sense to me unless multiplication of two floats produces some 'non-addable' type):

src\main.rs(14,9): error E0369: 不能应用二进制操作 +输入 ::Output
帮助:运行rustc --explain E0369查看详细解释
注意:::Output

src\main.rs(14,9): error E0369: binary operation + cannot be applied to type <T as std::ops::Mul>::Output
help: run rustc --explain E0369 to see a detailed explanation
note: an implementation of std::ops::Add might be missing for <T as std::ops::Mul>::Output

Rust 编译器 rustc 1.11.0 (9b21dcd6a 2016-08-15)
代码类似于 this 示例.导致我的代码出错的区别是什么?

Rust compiler rustc 1.11.0 (9b21dcd6a 2016-08-15)
The code is similar to this example. What's the difference that makes my code wrong?

推荐答案

错误信息告诉您该怎么做:您需要为 添加一个 Add 实现.::输出.

The error message tells you what to do: you need to add an Add implementation for <T as Mul>::Output.

你可以通过在你的 impl 上添加一个 trait bound 来实现:

You can do so by adding a trait bound on your impl as such:

use std::ops::Mul;
use std::ops::Add;

struct Vec2<T: Copy>
{
    x: T,
    y: T,
}

impl<T> Vec2<T>
    where T: Copy + Mul,
          <T as Mul>::Output: Add<Output=T>
{
    fn magnitude_squared(&self) -> T {
        self.x * self.x + self.y * self.y
    }
}

fn main() {
    let x = Vec2 { x: 1f32, y: 1f32 };
    println!("{}", x.magnitude_squared());
}

添加了 Copy 以简化此答案.

The Copy was added to simplify this answer.

这篇关于使用具有泛型类型的运算符时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆