Editor's note: This question's example is from a version of Rust prior to 1.0 and references types and methods no longer found in Rust. The answers still contain valuable information.
The following code
let mut numbers = new_serial.as_bytes().iter().map(|&x| (x - 48));
let sum = numbers.sum();
results in the following error:
std::iter::Map<,&u8,u8,std::slice::Items<,u8>>` does not implement any method in scope named `sum`
What must I do to sum an array of bytes?
The following works:
for byte in new_serial.as_bytes().iter() {
sum = sum + (byte - 48);
}
|&x| (x - 48)
, those parentheses are unnecessary;|&x| x - 48
will work fine.sum += byte - 48;
for the manual loop. Also, you use a manual fold:numbers.iter().fold(0, |s, &x| s + x - 48)
.sum
is onIterator
.