[英]Rust: Create an Iterator out of Default and Succ?
我在回購中有以下代碼:
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()
系列迭代器,但它使用Add
和One
數字特征來生成項目。 你可以這樣做(這個想法與你的基本相同,但是由於One
trait的使用,這個版本稍微更通用):
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);
}
}
( 在這里試試)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.