0부터 n까지의 숫자를 더하는 함수를 작성하고 싶습니다. (이상적으로 이것은 모든 숫자에 대해 일반적인 것이지만 i32
으로 해결할 것입니다).녹에서 숫자의 범위를 어떻게 합산 할 수 있습니까?
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));
}
나는 다음과 같은 컴파일러 오류
내가해야합니까? 명시적인 범위/특성을 선언 하시겠습니까?
당신은'범위'유형의 단일 요소의 배열로 만드는 (일명'[표준 : 작전 :: 범위 을 1]'). 아마도 연산자 우선 순위를 변경하여'n '에'sum()'을 호출하지 않는'(0 .. n)'을 의미 할 것입니다. ([Playground Example] (https://play.rust-lang.org/?gist=b27932d99482f3ddd62697b62f1fe28c&version=stable&backtrace=0) –
Aurora0001