本文介绍了我如何要求泛型类型在泛型函数中实现类似Add,Sub,Mul或Div的操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Rust中实现一个泛型函数,其中对参数的唯一要求是应定义乘法运算.我正在尝试实现通用的电源",但将使用一个更简单的cube函数来说明问题:

I'm trying to implement a generic function in Rust where the only requirement for the argument is that the multiplication operation should be defined. I'm trying to implement a generic "power", but will go with a simpler cube function to illustrate the problem:

use std::ops::Mul;

fn cube<T: Mul>(x: T) -> T {
    x * x * x
}

fn main() {
    println!("5^3 = {}", cube(5));
}

编译时出现此错误:

error[E0369]: binary operation `*` cannot be applied to type `<T as std::ops::Mul>::Output`
 --> src/main.rs:4:5
  |
4 |     x * x * x
  |     ^^^^^^^^^
  |
  = note: an implementation of `std::ops::Mul` might be missing for `<T as std::ops::Mul>::Output`

这是什么意思?我选择了错误的特征吗?我该如何解决?

What does this mean? Did I choose the wrong trait? How can I resolve this?

推荐答案

让我们细分一下您的示例:

Let's break down your example a bit:

fn cube<T: Mul>(x: T) -> T {
    let a = x * x;
    let b = a * x;
    b
}

ab的类型是什么?在这种情况下,a的类型是<T as std::ops::Mul>::Output-错误消息听起来很熟悉?然后,我们尝试再次将该类型乘以x,但是不能保证Output可以乘以任何东西!

What are the types of a and b? In this case, the type of a is <T as std::ops::Mul>::Output — sound familiar from the error message? Then, we are trying to multiply that type by x again, but there's no guarantee that Output is able to be multiplied by anything!

让我们做最简单的事情,说T * T需要产生一个T:

Let's do the simplest thing and say that T * T needs to result in a T:

fn cube<T: Mul<Output = T>>(x: T) -> T {
    x * x * x
}

不幸的是,这给出了两个类似的错误:

Unfortunately, this gives two similar errors:

error[E0382]: use of moved value: `x`
 --> src/lib.rs:6:9
  |
6 |     x * x * x
  |     -   ^ value used here after move
  |     |
  |     value moved here
  |
  = note: move occurs because `x` has type `T`, which does not implement the `Copy` trait

这是因为 Mul特质按值接受参数,因此我们添加Copy,以便我们可以重复这些值.

Which is because the Mul trait takes arguments by value, so we add the Copy so we can duplicate the values.

我也切换到了where子句,因为我更喜欢它,并且拥有这么多的内联很笨拙:

I also switched to the where clause as I like it better and it is unwieldy to have that much inline:

fn cube<T>(x: T) -> T
where
    T: Mul<Output = T> + Copy
{
    x * x * x
}

另请参阅:

  • How do I implement the Add trait for a reference to a struct?
  • How to write a trait bound for adding two references of a generic type?

这篇关于我如何要求泛型类型在泛型函数中实现类似Add,Sub,Mul或Div的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 09:50