How to reduce a slice?

This should be very simple, but the quick fix suggestion doesn't work, and ChatGPT can't suggest something that works. No combination of '&'s and '*'s that I have tried work.
This doesn't compile.

fn main() {
    let product = [1,2,3,4,5,6].iter().reduce(|a, b| a * b).unwrap();
    println!("{:?}", product);
}

Playground link

Can you use .into_iter, i.e


fn main() {
    let product = [1,2,3,4,5,6].into_iter().reduce(|a,b| a * b).unwrap();

    println!("{:?}", product);
}


I'm trying to reduce an array I don't own.

Is fold acceptable?


fn main() {
    let product = [1,2,3,4,5,6].iter().fold(1, |a,b| a * *b);

    println!("{:?}", product);
}

1 Like

Yes, thank you. This works:

fn main() {
    let arr = [1,2,3,4,5,6];
    let slice = &arr;
    let product = slice.iter().fold(1, |a,b| a * b);

    println!("{:?}", product);
}

@anon80458984 has answered your question. But just for kicks here is another variation that copies each value so that integers, rather than integer references, are reduced. This works only if the elements are Copy, which of course integers are.

let product = [1,2,3,4,5,6].iter().copied().reduce(|a,b| a * b).unwrap();

EDIT: The reason for the error you got (pasted below) is that reduce uses the first element as the initial accumulator, which without using copied is a reference to an integer. That means your closure has to return a reference, since it returns a new accumulator.

4 |     let product = s.iter().reduce(|a,b| a * b).unwrap();
  |                                         ^^^^^ expected `&{integer}`, found integer
  |
help: consider borrowing here
  |
4 |     let product = s.iter().reduce(|a,b| &(a * b)).unwrap();
  |                                         ++     +

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.