提供一中方法顺序访问一个聚合对象中的各个元素,而又不暴露(稳定)该对象的内部表示
工程目录
iterator.go
package Iterator 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++ } }
iterator_test.go
package Iterator import ( "fmt" "testing" ) func TestArrayIterator(t *testing.T) { array := []interface{}{1,3,9,2,8,7} a := 0 iterator := ArrayIterator{array: array, index: &a} for it := iterator; iterator.HasNext(); iterator.Next(){ index, value := it.Index(), it.Value().(int) for value != array[*index]{ fmt.Println("error") } fmt.Println(*index, value) } }