
在 Go 语言中,虽然没有像 Java 或 C++ 那样内置的迭代器接口,但我们可以通过 结构体 + 接口 + 闭包 的方式实现灵活的迭代器模式。这种方式不仅能统一遍历逻辑,还能隐藏集合内部结构,提升代码可读性和复用性。
迭代器模式提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。核心是将“遍历”行为从集合中分离出来,交给独立的迭代器处理。
在 Golang 中,我们通常通过定义一个包含 Next() 和 Value() 方法的接口来模拟迭代器行为:
type Iterator interface {
Next() bool
Value() interface{}
}
以一个字符串切片为例,构建一个基础迭代器:
立即学习“go语言免费学习笔记(深入)”;
type SliceIterator struct {
slice []string
index int
}
func (it *SliceIterator) Next() bool {
if it.index < len(it.slice) {
it.index++
return true
}
return false
}
func (it *SliceIterator) Value() interface{} {
return it.slice[it.index-1]
}
使用示例:
data := []string{"apple", "banana", "cherry"}
iter := &SliceIterator{slice: data}
for iter.Next() {
fmt.Println(iter.Value())
}
输出结果为每行打印一个水果名称,实现了安全、可控的遍历。
Go 1.18 引入泛型后,我们可以写出更通用的迭代器。以下是一个适用于任意类型切片的泛型迭代器:
type SliceIterator[T any] struct {
slice []T
index int
}
func NewSliceIterator[T any](s []T) *SliceIterator[T] {
return &SliceIterator[T]{slice: s}
}
func (it *SliceIterator[T]) Next() bool {
if it.index < len(it.slice) {
it.index++
return true
}
return false
}
func (it *SliceIterator[T]) Value() T {
return it.slice[it.index-1]
}
调用方式:
nums := []int{1, 2, 3}
iter := NewSliceIterator(nums)
for iter.Next() {
fmt.Println(iter.Value()) // 输出 1, 2, 3
}
这种写法避免了重复实现,提高了类型安全性。
对于简单场景,可以用闭包快速构造一个函数式迭代器:
func NewCounterIterator(max int) func() (int, bool) {
count := 0
return func() (int, bool) {
count++
if count <= max {
return count, true
}
return 0, false
}
}
使用方式:
next := NewCounterIterator(3)
for {
val, ok := next()
if !ok {
break
}
fmt.Println(val)
}
这种方式适合临时遍历需求,无需定义结构体和接口,简洁高效。
基本上就这些。Golang 虽无原生迭代器语法,但通过接口、泛型和闭包可以轻松实现符合工程实践的遍历逻辑。关键是根据场景选择合适的方式:结构化用结构体,通用性考虑泛型,临时任务可用闭包。
以上就是如何用Golang实现迭代器遍历集合_Golang 迭代器模式集合遍历实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号