对于非递归类型的无限递归编译错误

时间:2017-06-03 17:32:07

标签: rust

我有一个通用特征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等荒谬的类型?

0 个答案:

没有答案