本文主要是介绍go语言数组动态扩容,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
package mainimport ("errors""fmt"
)//定义数组结构体
type Array struct{data []intlength int
}//为数组分配空间
func NewArray(capacity uint) *Array{if capacity == 0 {return nil}else{return &Array{data : make([] int, capacity, capacity),length : 0,}}
}//获得数组长度
func (this *Array)Len() int{return this.length
}//判断索引是否越界
func (this *Array)isIndexOutOfRange(index uint) bool{if index >= uint(cap(this.data)) {return true}else {return false}
}//在数组中找寻索引值
func (this *Array)Find(index uint) (int, error){if this.isIndexOutOfRange(index) {return -1,errors.New("this is out range")}else {return this.data[index], nil}
}//数组制定位置插入数值
func (this *Array) Insert(index uint, v int) error {if this.Len() == cap(this.data) {return errors.New("full array")}if index != uint(this.length) && this.isIndexOutOfRange(index) {return errors.
这篇关于go语言数组动态扩容的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!