// interface.go type ILinkList[T any] interface { // Iterator 获取迭代器函数 // @param ctx // @return func() (T, bool): data, isNull Iterator(ctx context.Context) func() (T, bool) } // linklist.go type LinkList[T any] struct { head *node[T] tail *node[T] cnt int } func (l *LinkList[T]) Iterator(ctx context.Context) func() (T, bool) { p := l.head // 此处使用闭包的特性,实现迭代器操作 return func() (T, bool) { if p == nil { var t T // 这里不能直接返回nil,一旦T不是指针的话,返回nil会出现panic,所以此处需要先创建其变量再返回 return t, true } data := p.data p = p.next return data, false } } func NewLinkList[T any]() ILinkList[T] { return &LinkList[T]{} } // types.go type node[T any] struct { data T next *node[T] } func newNode[T any]() *node[T] { return &node[T]{} }