我想编写一个函数,将零到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`

我必须声明明确的界限/特征吗?

最佳答案

问题是您要创建一个范围数组(方括号),但您只想要该范围(定义折叠的范围)。

另一件事是范围语法(..)仅包含下限。它不包括上限,因此您必须迭代到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));
}

关于rust - 如何在Rust中求和一定范围的数字?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40194949/

10-12 04:07
查看更多