企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 示例 ### 迭代器 <details> <summary>main.go</summary> ``` package main import "fmt" // 集合 type collection interface { createIterator() iterator } type userCollection struct { users []*user } func (u *userCollection) createIterator() iterator { return &userIterator{ users: u.users, } } // 迭代器 type iterator interface { hasNext() bool getNext() *user } // 具体迭代器 type userIterator struct { index int users []*user } func (u *userIterator) hasNext() bool { if u.index < len(u.users) { return true } return false } func (u *userIterator) getNext() *user { if u.hasNext() { user := u.users[u.index] u.index++ return user } return nil } // 客户端代码 type user struct { name string age int } func main() { user1 := &user{ name: "a", age: 30, } user2 := &user{ name: "b", age: 20, } userCollection := &userCollection{ users: []*user{user1, user2}, } iterator := userCollection.createIterator() for iterator.hasNext() { user := iterator.getNext() fmt.Printf("User is %+v\n", user) } } ``` </details> <br /> 输出 ``` User is &{name:a age:30} User is &{name:b age:20} ```