我有一个迭代器,可以生成斐波那契数列。我将类型限制为u32
,但现在我很难使其适用于任何数值类型。
下面是可工作的、非通用代码:
struct Fib {
value: u32,
next: u32,
}
impl Fib {
fn new( a : u32, b : u32 ) -> Fib {
Fib { value : a, next : b }
}
}
impl Iterator for Fib {
type Item = u32;
fn next(&mut self) -> Option<u32> {
let value = self.value;
let next = self.value + self.next;
self.value = self.next;
self.next = next;
Some( value )
}
}
//////////////////////////////////////////////////
fn main() {
let fib = Fib::new( 1, 2 );
let sum = fib.filter( |x| { x % 2 == 0 })
.take_while( |&x| { x <= 4000000 })
.fold( 0, |sum, x| { sum + x });
println!("{}", sum);
}
问题在于实现
Iterator
需要对Num
进行约束,但我不知道如何表达这个约束: impl <T : Num> Iterator for Fib<T> { ... }
生成:
use of undeclared trait name `Num`
当我尝试使用use std::num::{Num}
或者use num::traits::{Num}
时,系统提示这些模块不存在。