ゼロからnまでの数値を合計する関数を記述したいと思います。 (理想的には、これはすべての数字に対して一般的ですが、私はi32
のために解決します)。どのようにしてRustの数値の範囲を合計できますか?
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`
を
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));
}
は、私は次のコンパイラエラーを取得します
私はそうですか明示的な境界/特質を宣言するか?
あなたは 'レンジ'タイプ(別名 '[STD :: OPS ::レンジ; 1]')の単一要素の配列を作成しています。おそらく '(0 .. n)'を意味するだけで、演算子の優先順位を変更して、 'n 'に' sum() 'を呼び出さないようにするだけです。 ([Playground Example](https://play.rust-lang.org/?gist=b27932d99482f3ddd62697b62f1fe28c&version=stable&backtrace=0) –
Aurora0001