Is there any way to collapse with an index in Rust?

In Ruby, if I had an array a = [1, 2, 3, 4, 5] , and I wanted to get the sum of each element for my index, I could do

 a.each.with_index.inject(0) {|s,(i,j)| s + i*j} 

Is there an idiomatic way to do the same in Rust? I still have

 a.into_iter().fold(0, |x, i| x + i) 

But this does not account for the index, and I cannot find a way to get it to account for the index. Is this possible, and if so, how?

+5
source share
1 answer

You can bind it with enumerate :

 fn main() { let a = [1, 2, 3, 4, 5]; let b = a.into_iter().enumerate().fold(0, |s, (i, j)| s + i * j); println!("{:?}", b); // Prints 40 } 
+11
source

Source: https://habr.com/ru/post/1261113/


All Articles