gpt4 book ai didi

go - 在这两个迭代器中减少重复的好方法是什么?

转载 作者:数据小太阳 更新时间:2023-10-29 03:03:10 28 4
gpt4 key购买 nike

我编写了一个迭代器以便更轻松地访问某些分页数据库结果,但减少重复的好方法是什么?

foo_iterator.go

type FooIterator struct {
hasNext bool
app *App
batchSize int
}

func NewFooIterator(app *App, batchSize int) *FooIterator {
return &FooIterator{
hasNext: true,
app: app,
batchSize: batchSize,
}
}

func (it *FooIterator) HasNext() bool {
return it.hasNext
}

func (it *FooIterator) Next() []*model.Foo {
offset := 0
batch := it.app.GetAllFoosInPages(offset, it.batchSize)
if len(batch) < it.batchSize {
it.hasNext = false
}
offset += it.batchSize
return batch
}

bar_iterator.go

type BarIterator struct {
hasNext bool
app *App
batchSize int
}

func NewBarIterator(app *App, batchSize int) *BarIterator {
return &BarIterator{
hasNext: true,
app: app,
batchSize: batchSize,
}
}

func (it *BarIterator) HasNext() bool {
return it.hasNext
}

func (it *BarIterator) Next() []*model.Bar {
offset := 0
batch := it.app.GetAllBarsInPages(offset, it.batchSize)
if len(batch) < bi.batchSize {
it.hasNext = false
}
offset += it.batchSize
return batch
}

用法

fooIterator := NewFooIterator(a, 100)

for fooIterator.HasNext() {
fooBatch := rolesIterator.Next()
// Do stuff
}

它们非常相似,肯定有一些共享代码的好方法,但我尝试的一切似乎都很尴尬。

最佳答案

编写一个通用迭代器调用一个函数来获取更多数据:

type Iterator struct {
more func(offset int, batchSize int) (int, interface{})
hasNext bool
batchSize int
offset int
}

func (it *Iterator) HasNext() bool {
return it.hasNext
}

func (it *Iterator) Next() interface{} {
n, batch := it.more(it.offset, it.batchSize)
if n < it.batchSize {
it.hasNext = false
}
it.offset += n
return batch
}

像这样使用它:

func NewFooIterator(app *App, batchSize int) *Iterator {
return &Iterator{
hasNext: true,
batchSize: batchSize,
more: func(offset int, batchSize int) (int, interface{}) {
batch := it.app.GetAllFoosInPages(offset, it.batchSize)
return len(batch), batch
},
}
}

fooIterator := NewFooIterator(a, 100)

for fooIterator.HasNext() {
fooBatch := fooIterator.Next().([]*model.Foo)
// Do stuff
}

关于go - 在这两个迭代器中减少重复的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50280878/

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