How can I reduce number of casting

I've this code, which is having 4 casting as in single line, which I feel is annoying, is there a way to avoid/reduce them?

fn main() {
    let series = [
        30,21,29,31,40,48,53,47,37,39,31,29,17,9,20,24,27,35,41,38,
        27,31,27,26,21,13,21,18,33,35,40,36,22,24,21,20,17,14,17,19,
        26,29,40,31,20,24,18,26,17,9,17,21,28,32,46,33,23,28,22,27,
        18,8,17,21,31,34,44,38,31,30,26,32];

    series[..slen].iter().zip(&series[slen..])
        .map(|(&a, &b)| (b as f32 - a as f32) / slen as f32).sum::<f32>() / slen as f32
}

You could avoid casting slen twice by storing the result in a variable.

You could make the array of numbers [f32] to begin with, and not have to cast b or a. (But your numbers all fit in u8 so this would be wasteful of memory.)

Rust deliberately avoids implicit numeric type coercions (like you'd see in C), so if your code is converting numeric types, it will tend to contain a lot of casts.

4 Likes

Why not:

...(b - a) as f32...
4 Likes