大家好,我是 frank,「Golang语言开发栈」公众号作者。
01 、介绍
在 Go 1.23 版本中,新引入迭代器功能,这是一个新的语言特性,旨在简化对集合和其他数据结构的迭代操作。迭代器提供了一种更直接、更灵活的方式来遍历集合,同时避免了传统方法中的一些局限性,例如通道的性能开销和复杂性。
本文我们介绍 Go 1.23 中迭代器的使用方式。
02 、迭代器实现原理
Range expression 1st value 2nd value
function, 0 values f func(func() bool)
function, 1 value f func(func(V) bool) value v V
function, 2 values f func(func(K, V) bool) key k K v V
For a function f, the iteration proceeds by calling f with a new, synthesized yield function as its argument. If yield is called before f returns, the arguments to yield become the iteration values for executing the loop body once. After each successive loop iteration, yield returns true and may be called again to continue the loop. As long as the loop body does not terminate, the "range" clause will continue to generate iteration values this way for each yield call until f returns. If the loop body terminates (such as by a break statement), yield returns false and must not be called again.
03 、迭代器使用方式
迭代器函数通常由 for range
调用,示例代码:
// 迭代器 func(func() bool)
package main
import "fmt"
// 迭代器
func f0(yield func() bool) {
for i := 0; i < 10; i++ {
if !yield() {
return
}
}
}
func main() {
for range f0 {
fmt.Println("iter")
}
}
// 迭代器 f func(func(V) bool)
package main
import "fmt"
func f1(yield func(k int) bool) {
for i := 0; i < 10; i++ {
if !yield(i) {
return
}
}
}
func main() {
for k := range f1 {
fmt.Println(k)
}
}
// 迭代器 f func(func(K, V) bool)
package main
import "fmt"
// 迭代器
func f2(yield func(k int, v string) bool) {
for i := 0; i < 10; i++ {
if !yield(i, fmt.Sprintf("No.%d", i)) {
return
}
}
}
func main() {
for k, v := range f2 {
fmt.Printf("k:%d, v:%s\n", k, v)
}
}
// 迭代器 break
package main
import "fmt"
func f2(yield func(k int, v string) bool) {
for i := 0; i < 10; i++ {
if !yield(i, fmt.Sprintf("No.%d", i)) {
return
}
}
}
func main() {
for k, v := range f2 {
if k == 5 {
fmt.Println("iter break")
break
}
fmt.Printf("k:%d, v:%s\n", k, v)
}
}
04 、总结
本文我们主要通过示例代码,介绍 Go 1.23 引入的语言新特性迭代器怎么使用,感兴趣的读者朋友们,不妨在本地运行示例代码,举一反三,思考一下有哪些使用场景。
参考资料:
动动发财的小手,点赞和在看。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有