我正在尝试在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
和b
?在这种情况下,a
的类型是<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
这是因为Mul
trait takes arguments by value,所以我们添加Copy
所以我们可以复制值。
我也切换到where
条款,因为我更喜欢它,并且有这么多内联是不实用的:
fn cube<T>(x: T) -> T
where
T: Mul<Output = T> + Copy
{
x * x * x
}
也可以看看:
绑定的T: Mul
并不意味着二元运算符的结果也是T
类型。结果类型是此特征的关联类型:Output
。
另一个问题是在Rust 1.0之前,运算符traits从pass-by-reference切换到pass-by-value。在通用代码中,这可能是一个痛苦的屁股(至少现在),因为这些运算符消耗它们的操作数,除非你还要求类型为Copy
。
只是为了完整性(如果你不想要Copy
),让我添加一些可能的替代方向的信息。
为了通用代码,鼓励“数字类型”的作者提供这些运算符特征的其他非消费实现,这样您就不需要Copy
或Clone
。例如,标准库已提供以下实现:
f64 implements Mul< f64>
f64 implements Mul<&f64>
&f64 implements Mul< f64>
&f64 implements Mul<&f64>
这些实现中的每一个都具有f64
作为Output
类型。直接利用这些特征并不是很好:
fn cube<T>(x: &T) -> T
where
for<'a> T: Mul<&'a T, Output = T>,
for<'a, 'b> &'a T: Mul<&'b T, Output = T>,
{
x * x * x
}
最终,我们可能会得到一些(稍微)更高级别的特征,这会降低噪音。例如:T: Mul2
可能意味着T: Mul<T> + Mul<&T>
和&T: Mul<T> + Mul<&T>
,但在撰写本文时,Rust编译器似乎无法处理这个问题。至少我无法成功编译以下代码:
use std::ops::Mul;
pub trait Mul2
where
Self: Mul<Self, Output = Self>,
Self: for<'a> Mul<&'a Self, Output = Self>,
for<'a> &'a Self: Mul<Self, Output = Self>,
for<'a, 'b> &'a Self: Mul<&'b Self, Output = Self>,
{
}
impl<T> Mul2 for T
where
T: Mul<T, Output = T>,
T: for<'a> Mul<&'a T, Output = T>,
for<'a> &'a T: Mul<T, Output = T>,
for<'a, 'b> &'a T: Mul<&'b T, Output = T>,
{
}
fn cube<T: Mul2>(x: &T) -> T {
x * x * x
}
fn main() {
let c = cube(&2.3);
println!("Hello, world! {}", c)
}
我认为可以说这方面的事情会有所改善。目前,在Rust中一般实现数值算法的能力并不像我希望的那样好。