我想写一个函数,将数字从零到n求和(理想情况下,这对所有数字都是通用的,但我会接受i32
).
mod squares {
pub fn sum_from_zero( n: i32) -> i32 {
[0 .. n].fold(0, |a, b| a + b)
}
}
#[test]
fn test_sum_from_zero() {
assert_eq!(15, squares::sum_from_zero(5));
}
我发现以下编译器错误:
src/lib.rs:5:18: 5:22 error: no method named `fold` found for type `[std::ops::Range<i32>; 1]` in the current scope
src/lib.rs:5 [0 .. n].fold(0, |a, b| a + b)
^~~~
src/lib.rs:5:18: 5:22 note: the method `fold` exists but the following trait bounds were not satisfied: `[std::ops::Range<i32>; 1] : std::iter::Iterator`, `[std::ops::Range<i32>] : std::iter::Iterator`
我也试过sum()
次:
mod squares {
pub fn sum_from_zero( n: i32) -> i32 {
[0 .. n].sum()
}
}
#[test]
fn test_sum_from_zero() {
assert_eq!(15, squares::sum_from_zero(5));
}
并出现以下编译器错误:
src/lib.rs:5:18: 5:21 error: no method named `sum` found for type `[std::ops::Range<i32>; 1]` in the current scope
src/lib.rs:5 [0 .. n].sum()
^~~
src/lib.rs:5:18: 5:21 note: the method `sum` exists but the following trait bounds were not satisfied: `[std::ops::Range<i32>; 1] : std::iter::Iterator`, `[std::ops::Range<i32>] : std::iter::Iterator`
src/lib.rs:5:18: 5:21 error: no method named `sum` found for type `[std::ops::Range<i32>; 1]` in the current scope
src/lib.rs:5 [0 .. n].sum()
^~~
src/lib.rs:5:18: 5:21 note: the method `sum` exists but the following trait bounds were not satisfied: `[std::ops::Range<i32>; 1] : std::iter::Iterator`, `[std::ops::Range<i32>] : std::iter::Iterator`
我必须声明明确的界限/特征吗?