# Go中的Array和Slice

stonekun · · 1480 次点击 · · 开始浏览

# Go中的Array和Slice

## 操作

### extend

``````func Extend(slice []int, element int) []int {
n := len(slice)
slice = slice[0 : n+1]
slice[n] = element
return slice
}
``````

``````func main() {
var iBuffer [10]int
slice := iBuffer[0:0]
for i := 0; i < 20; i++ {
slice = Extend(slice, i)
fmt.Println(slice)
}
}

``````

``````func Extend(slice []int, element int) []int {
n := len(slice)
if n == cap(slice) {
// Slice is full; must grow.
// We double its size and add 1, so if the size is zero we still grow.
newSlice := make([]int, len(slice), 2*len(slice)+1)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0 : n+1]
slice[n] = element
return slice
}
``````

### copy

``````copy(newSlice, slice)
copy(slice[index+1:], slice[index:])
``````

### array to slice

``````var array = [n]int

slice = array[:]

slice = array[begin:end]
``````

### slice to array

``````在调用append方法的时候需要传入的是个数不定的element

func Append(slice []int, elements ...int) []int{

}

slice1 := []int{0, 1, 2, 3, 4}
slice2 := []int{55, 66, 77}
slice1 = Append(slice1, slice2...) // The '...' is essential!

``````

## nil slice 和 empty slice

``````var slice []int

slice = make([]int,0,0)
slice不等于nil
``````

cap len 操作

``````nil slice的cap和len的大小都为0

``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

# Go中的Array和Slice

## 操作

### extend

``````func Extend(slice []int, element int) []int {
n := len(slice)
slice = slice[0 : n+1]
slice[n] = element
return slice
}
``````

``````func main() {
var iBuffer [10]int
slice := iBuffer[0:0]
for i := 0; i < 20; i++ {
slice = Extend(slice, i)
fmt.Println(slice)
}
}

``````

``````func Extend(slice []int, element int) []int {
n := len(slice)
if n == cap(slice) {
// Slice is full; must grow.
// We double its size and add 1, so if the size is zero we still grow.
newSlice := make([]int, len(slice), 2*len(slice)+1)
copy(newSlice, slice)
slice = newSlice
}
slice = slice[0 : n+1]
slice[n] = element
return slice
}
``````

### copy

``````copy(newSlice, slice)
copy(slice[index+1:], slice[index:])
``````

### array to slice

``````var array = [n]int

slice = array[:]

slice = array[begin:end]
``````

### slice to array

``````在调用append方法的时候需要传入的是个数不定的element

func Append(slice []int, elements ...int) []int{

}

slice1 := []int{0, 1, 2, 3, 4}
slice2 := []int{55, 66, 77}
slice1 = Append(slice1, slice2...) // The '...' is essential!

``````

## nil slice 和 empty slice

``````var slice []int

slice = make([]int,0,0)
slice不等于nil
``````

cap len 操作

``````nil slice的cap和len的大小都为0

``````