gpt4 book ai didi

iterator - Rust:用 Default 和 Succ 创建一个迭代器?

转载 作者:行者123 更新时间:2023-11-29 08:14:56 25 4
gpt4 key购买 nike

我在 a repo 中有以下代码:

impl<Id> IdAllocator<Id> where
Id : Clone + Default + Add<u32, Id>,
{
pub fn new() -> IdAllocator<Id> {
IdAllocator {
next: Default::default()
}
}

// Produce an Id that hasn't been produced yet by this object.
pub fn allocate(&mut self) -> Id {
let ret = self.next.clone();
self.next = self.next + 1;
ret
}
}

但这似乎有点笨拙,特别是因为 Add 实例仅用作 succ 函数(按顺序生成下一个值)。我可以使用一些 Succ 类吗?如果是这样,标准库中是否已经有一些Iterator 构造已经执行了此Default+Succ 模式?

谢谢!

最佳答案

不,不幸的是,标准库中没有类似Succ 的东西。您能找到的最接近的是 range()迭代器系列,但是,它使用 AddOne 数字特征来生成项目。你可以这样做(这个想法与你的想法基本相同,但是由于 One 特性的使用,这个版本稍微更通用):

use std::num::One;
use std::default::Default;

struct IdAllocator<T> {
current: T
}

impl<T: Default> IdAllocator<T> {
#[inline]
pub fn new() -> IdAllocator<T> {
IdAllocator {
current: Default::default()
}
}
}

impl<T: Add<T, T>+One+Clone> Iterator<T> for IdAllocator<T> {
fn next(&mut self) -> Option<T> {
let next = self.current + One::one();
self.current = next.clone();
Some(next)
}
}

fn main() {
let a = IdAllocator::<uint>::new();
for i in a.take(10) {
println!("{}", i);
}
}

(试一试 here )

关于iterator - Rust:用 Default 和 Succ 创建一个迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26537009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com