如何在 Rust 中对数组、切片或 Vec 中的值求和?

编程入门 行业动态 更新时间:2024-10-27 07:21:26
本文介绍了如何在 Rust 中对数组、切片或 Vec 中的值求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

编者注:此问题的示例来自 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 中的值求和?

本文发布于:2023-11-30 10:38:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   切片   中对   如何在   Vec

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!