如何在Rust中总结一系列数字?

时间:2016-10-22 17:22:21

标签: rust

我想写一个函数来将数字从0加到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`

我是否必须声明显式边界/特征?

1 个答案:

答案 0 :(得分:11)

问题是你正在创建一个范围数组(方括号),但你只想要范围(定义了折叠)。

另一个问题是范围语法(..)仅包含下限。它不包含上限,因此您必须迭代n+1才能获得所需的结果。

mod squares {

    pub fn sum_from_zero( n: i32) -> i32 {
        (0 .. n+1).fold(0, |a, b| a + b)
    }
}

#[test]
fn test_sum_from_zero() {
    assert_eq!(15, squares::sum_from_zero(5));
}