On idiomatic Rust style


#1

I’m just wondering what the prefered accepted idiomatic style is for map/fold use in this situation. I have a collection of channels each of which delivers one value – using channels to deliver partial sums of a computation. Originally I had:

channels.iter().fold(0.0, |acc, i| acc + i.1.recv().unwrap())

which works fine and is not unreadable. But then there is:

channels.iter().map(|i| i.1.recv().unwrap()).fold(0.0, Add::add)

which works equally well, and is equally not unreadable. Is one more idiomatic Rust style than the other – assuming that there are no performance implications.


#2

I prefer (untested):

channels.iter().map(|i| i.1.recv().unwrap()).sum()


#3

Using sum() rather than fold(0.0, Add::add) gives a compilation error.


#4

When you experience and report an error here, it’s a good idea to tell the error exactly. There are two most probable sources of problems: older Rust standard library without the sum(), or insufficient type inferencing. The first problem is solved updating the compiler (or activating the feature on older Nightie), the second adding more type information.

You have three ways to give a hint to the Rustc type inferencer: adding a type annotation to the variable you assign the result to, adding a turbofish, or using type ascription in a Nightly. The most sure solution is the second:

channels.iter().map(|i| i.1.recv().unwrap()).sum::<f64>()


#5

I am using stable, with all external crates up to date. Using beta or nightly doesn’t feel like the right thing to do for application development. Yes, I should have put the error message, apologies for that. Giving an explicit type to the variable didn’t work, which surprised me. The type annotation on the sum call works fine, but looks sort of ugly. Is type ascription coming to stable?


#6

I try to write chained code as discrete steps because they are easier to refactor (ideally, each step on a separate line). So far my only exception is using flat_map or filter_map (which you could use to ignore errors).