游客发表
真正的Vector需要更多实用功能:
go
// 容量管理
func (v *Vector[T]) Reserve(capacity int) {
newItems := make([]T, len(v.items), capacity)
copy(newItems, v.items)
v.items = newItems
}// 迭代支持
func (v *Vector[T]) Range(f func(index int, item T) bool) {
for i, item := range v.items {
if !f(i, item) {
break
}
}
}// JSON序列化
func (v *Vector[T]) MarshalJSON() ([]byte, error) {
return json.Marshal(v.items)
}与container/list相比,超值服务器与挂机宝、
泛型编程一直是Go开发者翘首以盼的特性 ,需要注意这些优化点:
预分配策略
:根据使用场景设置合理的初始容量
go func NewWithCapacity[T any](capacity int) *Vector[T] { return &Vector[T]{items: make([]T, 0, capacity)} }内存池技术
:对于频繁创建的Vector对象
go var vectorPool = sync.Pool{ New: func() interface{} { return New[any]() }, }零拷贝优化
:批量操作时减少内存分配
go func (v *Vector[T]) AppendSlice(items []T) { v.items = append(v.items, items...) }在Web开发中的典型应用 :
go
// 处理API分页结果
type APIResponse[T any] struct {
Data Vector[T] json:"data"
Page int json:"page"
}func GetUserList(page int) APIResponse[User] {
vec := NewUser// ...填充数据
return APIResponse[User]{Data: *vec, Page: page}
}