即提供遍历功能函数
package main
import "log"
// Iterator
// 迭代器,即提供遍历功能函数
// 如sqlx的rows迭代器
type Iterator interface {
Index() int
Value() interface{}
HasNext() bool
Next()
}
type ArrayIterator struct {
array []interface{}
index *int
}
func (a *ArrayIterator) Index() int {
return *a.index
}
func (a *ArrayIterator) Value() interface{} {
return a.array[*a.index]
}
func (a *ArrayIterator) HasNext() bool {
return *a.index+1 <= len(a.array)
}
func (a *ArrayIterator) Next() {
if a.HasNext() {
*a.index++
}
}
func main() {
slice := []interface{}{1, 3, 9, 2, 8, 7}
a := 0
iter := ArrayIterator{array: slice, index: &a}
for it := iter; it.HasNext(); iter.Next() {
index := it.Index()
value := it.Value()
if value != slice[index] {
log.Println("error")
}
log.Println(index, value)
}
}
发表回复