# 03.3.6 使用切片的代码示例

希望slices.go中的代码能够扫除你对切片所有的困惑，本节代码分为5个部分。

第一部分包含切片的定义以及初始值的说明:

> ```go
> package main
>
> import "fmt"
>
> func main()  {
>    aSlice := []int{1, 2, 3, 4, 5}
>    fmt.Println(aSlice)
>    integer := make([]int,2)
>    fmt.Println(integer)
>    integer = nil
>    fmt.Println(integer)
> ```

第二部分展示了如何使用`[:]`以数组创建切片。注意，`[:]`操作只是将引用指向数组，并没有创建一份数组的拷贝:

> ```go
> anArray := [5]int{-1, -2, -3, -4, -5}
> refAnArray := anArray[:]
>
> fmt.Println(anArray)
> fmt.Println(refAnArray)
> anArray[4] = -100
> fmt.Println(refAnArray)
> ```

第三部分代码使用`make()`创建一个二维切片:

> ```go
> s := make([]byte,5)
> fmt.Println(s)
> twoD := make([][]int,3)
> fmt.Println(twoD)
> fmt.Println()
> ```

Go自动将切片的元素值初始化为对应切片类型的零值，例如int类型的零值是`0`，切片的零值是`nil`。记住，多维切片的元素类型是切片！

slices.go的第四部分，你将看到初始化二维数组的方法:

> ```go
> for i := 0; i < len(twoD);i++ {
>    for j := 0; j < 2; j++ {
>       twoD[i] = append(twoD[i], i*j)
>    }
> }
> ```

上述代码使用append()函数往切片中追加元素，切记不要使用不存在的索引值，否则你将看到`panic:runtime error: index out of range`。

最后一部分代码展示了如何使用`range`关键字打印二维切片的所有元素:

> ```go
> for _, x := range twoD {
>       for i,y := range x {
>          fmt.Println("i:",i, "value:",y)
>       }
>
>       fmt.Println()
>    }
>
> }
> ```

执行slices.go，你将看到如下输出:

> $ go run slices.go
>
> \[1 2 3 4 5]\[0 0] \[]\[-1 -2 -3 -4 -5] \[-1 -2 -3 -4 -5]
>
> \[-1 -2 -3 -4 -100]
>
> \[0 0 0 0 0]\[\[]
>
> i: 0 value: 0 i: 1 value: 0
>
> i: 0 value: 0 i: 1 value: 1
>
> i: 0 value: 0 i: 1 value: 2

由于切片的零值是`nil`，所以二维切片中的切片元素被初始化为`nil`，打印出来就是空的。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wskdsgcf.gitbook.io/mastering-go-zh-cn/3-go-ji-ben-shu-ju-lei-xing/03.3/03.3.6.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
