定义迭代器接口并用结构体实现,通过Next、Value和Reset方法安全遍历集合,利用Go接口与闭包特性实现不同类型集合的统一访问,如整型切片和字符串映射,提升代码扩展性与维护性。

在Go语言中实现迭代器模式,可以为自定义集合提供统一、安全的遍历方式,避免暴露内部数据结构。虽然Go没有像Java或C#那样的接口约束和类继承体系,但通过结构体、接口和闭包,依然能简洁高效地实现迭代器模式。
Iterator interface {
Next() bool
Value() interface{}
Reset()
}
其中:
type IntSliceCollection struct {
items []int
}
func (c *IntSliceCollection) CreateIterator() Iterator {
return &IntSliceIterator{
collection: c,
index: 0,
}
}
type IntSliceIterator struct {
collection *IntSliceCollection
index int
}
func (it *IntSliceIterator) Next() bool {
return it.index
}
func (it *IntSliceIterator) Value() interface{} {
if it.index >= len(it.collection.items) {
return nil
}
value := it.collection.items[it.index]
it.index++
return value
}
func (it *IntSliceIterator) Reset() {
it.index = 0
}
func main() {
collection := &IntSliceCollection{items: []int{1, 2, 3, 4, 5}}
iter := collection.CreateIterator()
for iter.Next() {
fmt.Println("Value:", iter.Value())
}
}
输出结果为逐行打印 1 到 5。
type MapCollection struct {
data map[string]int
keys []string
}
其迭代器可按 key 的顺序返回键值对。只要实现 Iterator 接口,就能用相同方式遍历。
立即学习“go语言免费学习笔记(深入)”;
基本上就这些。Go的结构体组合和接口机制让迭代器模式实现变得直观,同时保持类型安全和扩展性。这种模式在处理复杂数据结构或需要统一访问方式的场景中特别有用。
以上就是Golang迭代器模式自定义集合遍历实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号