删除 index 处时元素,使用 append(slice[:index],slice[index+1:]...)
语法
简单写下声明语句
1
var identifier []type
Make 和 New
new 返回指针地址
make 返回第一个元素,可预设内存空间,避免未来的内存拷贝
1
// 返回指针
2
mySlice1 :=new([]int)
3
// 返回第一个元素
4
mySlice2 :=make([]int, 0)
5
mySlice3 :=make([]int, 10)
6
mySlice4 :=make([]int, 10, 20)
切片常见问题
切片相互赋值
内置函数 append 将元素追加到切片末尾。
当切片有足够容量时,自动追加到当前切片的底层数组中
当切片容量不足时,将分配新的底层数组,并将元素追加进新数组,最终返回新数组
The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice. It is therefore necessary to store the result of append, often in the variable holding the slice itself:
1
slice =append(slice, elem1, elem2)
2
slice =append(slice, anotherSlice...)
As a special case, it is legal to append a string to a byte slice, like this:
The copy built-in function copies elements from a source slice into a destination slice. (As a special case, it also will copy bytes from a string to a slice of bytes.) The source and destination may overlap. Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
评论