# 在 Go 中如何使用切片的容量和长度

``````vals := make([]int, 5)
for i := 0; i < 5; i++ {
vals = append(vals, i)
}
fmt.Println(vals)

``````

### 切片 vs 数组

``````var vals [20]int
for i := 0; i < 5; i++ {
vals[i] = i * i
}
subsetLen := 5

fmt.Println("The subset of our array has a length of:", subsetLen)

// Add a new item to our array
vals[subsetLen] = 123
subsetLen++
fmt.Println("The subset of our array has a length of:", subsetLen)

``````

``````var vals []int
for i := 0; i < 5; i++ {
vals = append(vals, i)
fmt.Println("The length of our slice is:", len(vals))
fmt.Println("The capacity of our slice is:", cap(vals))
}

// Add a new item to our array
vals = append(vals, 123)
fmt.Println("The length of our slice is:", len(vals))
fmt.Println("The capacity of our slice is:", cap(vals))

// Accessing items is the same as an array
fmt.Println(vals[5])
fmt.Println(vals[2])

``````

### 回到测试

``````vals := make([]int, 5)
for i := 0; i < 5; i++ {
vals = append(vals, i)
}
fmt.Println(vals)

``````

``````vals := make([]int, 5)
fmt.Println("Capacity was:", cap(vals))
for i := 0; i < 5; i++ {
vals = append(vals, i)
fmt.Println("Capacity is now:", cap(vals))
}

fmt.Println(vals)

``````

#### 直接使用索引写入而不是 `append`

``````vals := make([]int, 5)
for i := 0; i < 5; i++ {
vals[i] = i
}
fmt.Println(vals)

``````

``````package main

import "fmt"

func main() {
fmt.Println(keys(map[string]struct{}{
"dog": struct{}{},
"cat": struct{}{},
}))
}

func keys(m map[string]struct{}) []string {
ret := make([]string, len(m))
i := 0
for key := range m {
ret[i] = key
i++
}
return ret
}

``````

#### 使用 `0` 作为你的长度并指定容量

``````package main

import "fmt"

func main() {
fmt.Println(keys(map[string]struct{}{
"dog": struct{}{},
"cat": struct{}{},
}))
}

func keys(m map[string]struct{}) []string {
ret := make([]string, 0, len(m))
for key := range m {
ret = append(ret, key)
}
return ret
}

``````

### 如果 `append` 处理它，为什么我们还要担心容量呢？

``````package main

import "fmt"

func main() {
fmt.Println(keys(map[string]struct{}{
"dog":       struct{}{},
"cat":       struct{}{},
"mouse":     struct{}{},
"wolf":      struct{}{},
"alligator": struct{}{},
}))
}

func keys(m map[string]struct{}) []string {
var ret []string
fmt.Println(cap(ret))
for key := range m {
ret = append(ret, key)
fmt.Println(cap(ret))
}
return ret
}

``````

``````package main

import "fmt"

func main() {
fmt.Println(keys(map[string]struct{}{
"dog":       struct{}{},
"cat":       struct{}{},
"mouse":     struct{}{},
"wolf":      struct{}{},
"alligator": struct{}{},
}))
}

func keys(m map[string]struct{}) []string {
ret := make([]string, 0, len(m))
fmt.Println(cap(ret))
for key := range m {
ret = append(ret, key)
fmt.Println(cap(ret))
}
return ret
}

``````

### 总结

Jon 是一名软件顾问，也是 《Web Development with Go》 一书的作者。在此之前，他创立了 EasyPost，一家 Y Combinator 支持的创业公司，并在 Google 工作。

https://www.usegolang.com