我想写一个函数,将数字从零到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中如何修改一个盒装函数并将其赋回?

为什么我的梅森素数代码的指数越大,速度就越快?

无法在线程之间安全地发送future (&Q;)&错误

展开枚举变量并返回所属值或引用

如何在Rust中将选项<;选项<;字符串>;转换为选项<;选项&;str>;?

定义只有一些字段可以缺省的 struct

如何使用reqwest进行异步请求?

为什么 `Deref` 没有在 `Cell` 上实现?

类型生命周期绑定的目的是什么?

是否可以在不直接重复的情况下为许多特定类型实现一个函数?

.在 Rust 模块标识符中

具有多个键的 HashMap

在描述棋盘时如何最好地使用特征与枚举

如何基于常量在Rust中跳过一个测试

Rust Redis 中的 HSET 命令问题

Rust 引用元组和引用元组

如何在 Rust 中返回通用 struct

Rust,我如何正确释放堆分配的内存?

Rust 中的通用 From 实现

如何在 Rust 中构建一个 str