rust学习~slice迭代器

编程入门 行业动态 更新时间:2024-10-27 15:22:43

rust学习~slice<a href=https://www.elefans.com/category/jswz/34/1770528.html style=迭代器"/>

rust学习~slice迭代器

背景

pub fn iter(&self) -> Iter<'_, T>

查看Iter

结构体

pub struct Iter<'a, T>
whereT: 'a,
{ /* private fields */ }

对迭代器求和 sum

fn sum<S>(self) -> S
whereSelf: Sized, // 该函数只能在具有已知大小的类型上调用S: Sum<Self::Item>, // 指定和的类型,要求和的类型必须实现了 Sum trait

该函数返回 self 中所有项的和

  • Self 上的 Sized trait bound 表示该函数只能在具有已知大小的类型上调用,即只能在编译时确定大小的类型上调用该函数。
  • S 类型参数用于指定和的类型,而且要求和的类型必须实现了 Sum trait(这个 trait 用于进行求和操作)。

求和中的Sum Trait

std::iter::Sum
pub trait Sum<A = Self>: Sized {// Required methodfn sum<I>(iter: I) -> Selfwhere I: Iterator<Item = A>;
}

查看int32的Sum实现

// i32 的实现中,实现了如下trait
impl Sum<i32> for i32fn sum<I>(iter: I) -> i32
whereI: Iterator<Item = i32>,

阅读代码

// 具体实现方式
// 一个宏,它接受一系列整数类型作为参数,并为每个整数类型生成函数
// 这些函数可以计算相应整数类型的一组数字的和与积
integer_sum_product! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }// 宏的详细代码
// 为一系列整数类型实现 Sum 和 Product trait
macro_rules! integer_sum_product {// @impls 部分// 它是一个递归宏,用于为每个整数类型生成函数的实现// @impls 部分以两个参数 $zero 和 $one 开头,这两个参数分别是求和和求积操作的初始值// #[$attr:meta] 是一个标识求和和求积方法稳定性的元数据。这部分可以根据具体需求进行修改或省略// 为每个整数类型 $a 生成 Sum trait 的实现,初始值为 $zero// 为每个整数类型 $a 生成 Product trait 的实现,初始值为 $one(@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($(#[$attr]impl Sum for $a {fn sum<I: Iterator<Item=Self>>(iter: I) -> Self {// sum 方法的实现使用了 fold 方法来迭代累积计算和// 初始值为 $zero// 并在每次迭代中使用 #[rustc_inherit_overflow_checks] 注解来进行溢出检查// 迭代时,进行求和iter.fold($zero,#[rustc_inherit_overflow_checks]|a, b| a + b,)}}#[$attr]impl Product for $a {fn product<I: Iterator<Item=Self>>(iter: I) -> Self {iter.fold($one,#[rustc_inherit_overflow_checks]|a, b| a * b,)}}// 为引用类型生成的实现,允许对 &Self 进行求和#[$attr]impl<'a> Sum<&'a $a> for $a {fn sum<I: Iterator<Item=&'a Self>>(iter: I) -> Self {iter.fold(

更多推荐

rust学习~slice迭代器

本文发布于:2023-12-05 09:27:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1663811.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:迭代   rust   slice

发布评论

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

>www.elefans.com

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