我如何要求泛型类型在泛型函数中实现诸如 Add、Sub、Mul 或 Div 之类的操作? [英] How do I require a generic type implement an operation like Add, Sub, Mul, or Div in a generic function?
问题描述
我正在尝试在 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
}
a
和 b
的类型是什么?在这种情况下,a
的类型是
— 从错误消息中听起来很熟悉?然后,我们再次尝试将该类型乘以 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
trait 需要参数按值,所以我们添加了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
}
另见:
这篇关于我如何要求泛型类型在泛型函数中实现诸如 Add、Sub、Mul 或 Div 之类的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!