As in Swift ,it's very convenient to do "print((1...100).reduce(0){$0 + $1})" ,calculate 1..100.
What about in Rust?
As in Swift ,it's very convenient to do "print((1...100).reduce(0){$0 + $1})" ,calculate 1..100.
What about in Rust?
Starting from Rust 1.12 (released today!), you can use the Iterator::sum
method:
fn main() {
// return type is required here, sum is quite generic
println!("{}", (1..101).sum::<i32>());
}
More direct translation of your Swift code would use Iterator::fold
instead:
fn main() {
println!("{}", (1..101).fold(0, |a, b| a + b));
}
In either case, keep in mind that Rust's range is always exclusive at the end, hence 1..101
.
And the many folks using the Nightly compiler can also write it with an inclusive syntax:
#![feature(inclusive_range_syntax)]
fn main() {
println!("{}", (1 ... 100).sum::<u32>());
}
Actually starting from Rust 1.11. From today was the stabilization of Sum
, the trait used to implement .sum()
.
wow,It's cool.