我正在尝试在 Rust 中实现一个通用函数,其中参数的唯一要求是应该定义乘法运算。我正在尝试实现一个通用的“权力”,但会使用更简单的cube
函数来说明问题:
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`
这是什么意思?我是否选择了错误的特质?我该如何解决这个问题?
让我们稍微分解一下你的例子:
fn cube<T: Mul>(x: T) -> T {
let a = x * x;
let b = a * x;
b
}
有哪些类型a
and b
?在这种情况下,类型a
is <T as std::ops::Mul>::Output
— 错误消息听起来很熟悉?然后,我们尝试将该类型乘以x
再次,但不能保证Output
可以乘以任何东西!
让我们做最简单的事情并说T * T
需要产生一个T
:
fn cube<T: Mul<Output = T>>(x: T) -> T {
x * x * x
}
不幸的是,这会产生两个类似的错误:
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
这是因为MulTrait 按值获取参数 http://doc.rust-lang.org/std/ops/trait.Mul.html,所以我们添加Copy
所以我们可以复制这些值。
我也切换到了where
子句,因为我更喜欢它,而且有那么多内联是很笨拙的:
fn cube<T>(x: T) -> T
where
T: Mul<Output = T> + Copy
{
x * x * x
}
也可以看看:
- 如何实现结构体引用的 Add 特征? https://stackoverflow.com/q/28005134/155423
- 如何编写用于添加泛型类型的两个引用的特征绑定? https://stackoverflow.com/q/34630695/155423
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)