代码拉取完成,页面将自动刷新
package lang
import (
"errors"
"sync"
)
type Iterator[T any] struct {
list *List[T]
index int
lock *sync.RWMutex
}
func IteratorNew[T any](list *List[T], lock *sync.RWMutex) *Iterator[T] {
return &Iterator[T]{list: list, lock: lock}
}
func (it *Iterator[T]) HasNext() bool {
it.lock.RLock()
defer it.lock.RUnlock()
return it.index < it.list.Size()
}
func (it *Iterator[T]) Next() (*T, error) {
it.lock.Lock()
defer it.lock.Unlock()
if it.index < 0 || it.index >= len(it.list.elements) {
return nil, errors.New("index out of bounds")
}
item := it.list.elements[it.index]
it.index++
return &item, nil
}
type List[T any] struct {
elements []T
lock *sync.RWMutex
}
func ListNew[T any]() List[T] {
return List[T]{lock: &sync.RWMutex{}}
}
func (l *List[T]) Iterator() *Iterator[T] {
return IteratorNew[T](l, l.lock)
}
// Add 添加元素到List
func (l *List[T]) Add(element T) {
l.lock.Lock()
defer l.lock.Unlock()
l.elements = append(l.elements, element)
}
// AddAll 添加元素到List
func (l *List[T]) AddAll(element []T) {
l.lock.Lock()
defer l.lock.Unlock()
l.elements = append(l.elements, element...)
}
// Get 获取指定位置的元素
func (l *List[T]) Get(index int) (*T, error) {
l.lock.RLock()
defer l.lock.RUnlock()
if index < 0 || index >= len(l.elements) {
return nil, errors.New("index out of bounds")
}
return &l.elements[index], nil
}
// Remove 删除指定位置的元素
func (l *List[T]) Remove(index int) error {
l.lock.Lock()
defer l.lock.Unlock()
if index < 0 || index >= len(l.elements) {
return errors.New("index out of bounds")
}
l.elements = append(l.elements[:index], l.elements[index+1:]...)
return nil
}
// Size 返回List的大小
func (l *List[T]) Size() int {
l.lock.RLock()
defer l.lock.RUnlock()
return len(l.elements)
}
// Clear 清空List
func (l *List[T]) Clear() {
l.lock.Lock()
defer l.lock.Unlock()
l.elements = []T{}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。