编者注:此问题的示例来自 Rust 1.0 之前的版本,并且引用了 Rust 中不再存在的类型和方法.答案仍然包含有价值的信息.
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.
以下代码
let mut numbers = new_serial.as_bytes().iter().map(|&x| (x - 48)); let sum = numbers.sum();导致以下错误:
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?
以下工作:
for byte in new_serial.as_bytes().iter() { sum = sum + (byte - 48); } 推荐答案Iterator::sum 在 Rust 1.11.0 中得到了稳定.您可以从数组/切片/Vec 中获取迭代器,然后使用 sum:
Iterator::sum was stabilized in Rust 1.11.0. You can get an iterator from your array/slice/Vec and then use sum:
fn main() { let a = [1, 2, 3, 4, 5]; let sum: u8 = a.iter().sum(); println!("the total sum is: {}", sum); }需要特别注意的是,您需要指定求和的类型 (sum: u8),因为该方法允许多种实现.有关详细信息,请参阅 为什么 Rust 不能推断出 Iterator::sum 的结果类型?.
Of special note is that you need to specify the type to sum into (sum: u8) as the method allows for multiple implementations. See Why can't Rust infer the resulting type of Iterator::sum? for more information.
应用于您的原始示例:
let new_serial = "01234"; let sum: u8 = new_serial.as_bytes().iter().map(|&x| x - 48).sum(); println!("{}", sum);顺便说一句,如果您使用 b'0' 而不是 48 可能会更清楚.
As an aside, it's likely more clear if you use b'0' instead of 48.
更多推荐
如何在 Rust 中对数组、切片或 Vec 中的值求和?
发布评论