我有一个通用特征Trait<E: Float>
,该特征的通用结构Struct<E: Float>
,结构的Mul
实现,以及Trait
的通用函数与Mul
。
extern crate num;
use std::ops::Mul;
use num::traits::Float;
trait Trait<E: Float> {}
struct Struct<E: Float> (E);
impl<E: Float> Trait<E> for Struct<E> {}
impl<'a, 'b, E: Float> Mul<&'b Struct<E>> for &'a Struct<E>
where &'a E: Mul<&'b E, Output=E>
{
type Output = Struct<E>;
fn mul(self, rhs: &'b Struct<E>) -> Self::Output { unimplemented!() }
}
fn multiply<'a, E: Float, T: Trait<E>>(x: &'a T) -> T
where &'a T: Mul<&'a T, Output=T>
{
unimplemented!()
}
fn main() {
let matrix = multiply(&Struct(1.0));
}
这里没有任何内容似乎是递归的。但是,编译器错误通过触底反复出现:
error[E0275]: overflow evaluating the requirement `<&_ as std::ops::Mul<&_>>::Output`
--> src\main.rs:29:18
|
29 | let matrix = multiply(&Struct(1.0));
| ^^^^^^^^
|
= help: consider adding a `#![recursion_limit="128"]` attribute to your crate
= note: required because of the requirements on the impl of `std::ops::Mul<&Struct<_>>` for `&Struct<_>`
= note: required because of the requirements on the impl of `std::ops::Mul<&Struct<Struct<_>>>` for `&Struct<Struct<_>>`
= note: required because of the requirements on the impl of `std::ops::Mul<&Struct<Struct<Struct<_>>>>` for `&Struct<Struct<Struct<_>>>`
= note: required because of the requirements on the impl of `std::ops::Mul<&Struct<Struct<Struct<Struct<_>>>>>` for `&Struct<Struct<Struct<Struct<_>>>>`
...
以下是我在调试和尝试最小化此示例时发现的一些奇怪事实:
E: Zero
添加到Mul
的类型约束中,则堆栈跟踪将变为非确定性。有时,它会引用甚至未导入的特征,例如出现Complex
的{{1}}或Ratio
。_
的约束条件无关紧要。我可以创建一个新的特性,而不是使用E
,它可以做同样的事情。Float
而非为拥有值定义时才会发生这种情况。我需要做些什么才能使编译器失去像Mul
等荒谬的类型?