# Golang学习笔记-1.12 切片

xunk1900 · · 691 次点击 · · 开始浏览

# 多维数组

Go语言可以创建多维数组：

``````package main

import "fmt"

func test(a [3][2]string) {   //定义函数test，输入值为多维二维数组 a
for _, v1 := range a {
for _, v2 :=range v1 {
fmt.Printf("%s ", v2)  //两次循环得到其中一个值并输出
}
fmt.Println("\n")
}
}

func main() {
a := [3][2]string{  //定义一个二维数组
{"1x1", "1x2"},
{"2x1", "2x2"},
{"3x1", "3x2"},
}
test(a) //调用函数输出
}
``````

1x1 1x2
2x1 2x2
3x1 3x2

``````func main() {
var b [3][2]string
b[0][0] = "apple"
b[0][1] = "samsung"
b[1][0] = "microsoft"
b[2][0] = "AT&T"
b[2][1] = "T-Mobile"
fmt.Printf("\n")
test(b)
}
``````

# 切片

``````package main

import "fmt"

func main(){
a := [6]int{45, 56, 67, 78, 89, 90}
var b []int = a[1:5]  //创建一个切片 从 a[1] - a[4]
fmt.Println(b)
}
``````

`a[1:5]`创建了一个从`a[1] - a[4]`的切片。切片b的值为：`[56 67 78 89]`

``````package main

import "fmt"

func main(){
c := []int{6, 7, 8}  //创建一个数组 c ,并返回一个存储在 c 中的切片引用
fmt.Println(c)
}
``````

# 修改切片

``````package main

import "fmt"

func main(){
num := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9}   //定义数组 num
snum := num[2:8]   //创建切片从 num[2] - num[7]
fmt.Println("before change", num)   //输出改变前
for i := range snum {
snum[i]++  //给切片每个参数+1
}
fmt.Println("after change", num)   //输出改变后
}
``````

before change [1 2 3 4 5 6 7 8 9]
after change [1 2 4 5 6 7 8 9 9]

# 切片的长度和容量

slice的长度对应slice中的元素数量；长度不能超过容量。容量一般是从slice的开始为止到底层数组的结束位置。

``````package main

import "fmt"

func main(){
/*一个数组的第一个索引是从0开始，若想跳过0，则用1:的方式，第0个元素会自动初始化为空字符串*/
months := [...]string{1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"}
Q2 := months[4:7]  //第二季度
summer := months[6:9]   //夏天

fmt.Printf("length of Q2 is %d, capacity is %d\n", len(Q2), cap(Q2))
fmt.Printf("length of summer is %d, capacity is %d", len(summer), cap(summer))
}
``````

length of Q2 is 3, capacity is 9
length of summer is 3, capacity is 7

``````fmt.Println(summer[:20])   //报错panic:runtime error: slice bounds out of range
``````
``````package main

import "fmt"

func main(){
/*一个数组的第一个索引是从0开始，若想跳过0，则用1:的方式，第0个元素会自动初始化为空字符串*/
months := [...]string{1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"}
Q2 := months[4:7]  //第二季度
summer := months[6:9]   //夏天

//fmt.Printf("length of Q2 %d, capacity %d\n", len(Q2), cap(Q2))
//fmt.Printf("length of summer %d, capacity %d", len(summer), cap(summer))

//fmt.Println(summer[:20])  //报错panic:runtime error: slice bounds out of range

endlessSummer := summer[:5]  //扩展summer长度，并给切片endlessSummer
fmt.Println(endlessSummer)
fmt.Printf("the length os endlessSummer is %d, capacity is %d", len(endlessSummer), cap(endlessSummer))
}
``````

the length os endlessSummer is 5, capacity is 7

# 使用make创建切片

`func make（[]T，len，cap）`[]T 通过传递类型，长度和容量来创建切片。容量是可选参数, 默认值为切片长度。make 函数创建一个数组，并返回引用该数组的切片。

``````package main

import (
"fmt"
)

func main() {
i := make([]int, 5, 5)  //引用make函数创建切片
fmt.Println(i)
}
``````

# 追加切片元素

x ... T 在函数定义中表示该函数接受参数 x 的个数是可变的。这些类型的函数被称为可变函数。

``````package main

import "fmt"

func main(){
cars := []string{"Ferrari", "Honda", "Ford"}  //定义切片cars
fmt.Println(cars)
fmt.Println("old cars length is ", len(cars), "and capacity is ", cap(cars))  //输出cars的长度和容量
newcars := append(cars, "BYD")   //cars 切片增加新元素并定义给另一个切片newcars
fmt.Println(newcars)
fmt.Println("new cars length is ", len(newcars), "and capacity is ", cap(newcars))  //输出newcars长度和容量

}
``````

[Ferrari Honda Ford]
old cars length is 3 and capacity is 3
[Ferrari Honda Ford BYD]
new cars length is 4 and capacity is 6

# 多维切片

``````package main

import "fmt"

func main(){
/*多维数组*/
pls := [][]string {
{"C", "C++"},
{"JavaScript"},
{"Go", "Rust"},
}
for _, v1 := range pls {
for _, v2 := range v1 {
fmt.Printf("%s ", v2)
}
fmt.Printf("\n")
}
}
``````

C C++
JavaScript
Go Rust

1 回复  |  直到 2018-07-25 08:51:09

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

# 多维数组

Go语言可以创建多维数组：

``````package main

import "fmt"

func test(a [3][2]string) {   //定义函数test，输入值为多维二维数组 a
for _, v1 := range a {
for _, v2 :=range v1 {
fmt.Printf("%s ", v2)  //两次循环得到其中一个值并输出
}
fmt.Println("\n")
}
}

func main() {
a := [3][2]string{  //定义一个二维数组
{"1x1", "1x2"},
{"2x1", "2x2"},
{"3x1", "3x2"},
}
test(a) //调用函数输出
}
``````

1x1 1x2
2x1 2x2
3x1 3x2

``````func main() {
var b [3][2]string
b[0][0] = "apple"
b[0][1] = "samsung"
b[1][0] = "microsoft"
b[2][0] = "AT&T"
b[2][1] = "T-Mobile"
fmt.Printf("\n")
test(b)
}
``````

# 切片

``````package main

import "fmt"

func main(){
a := [6]int{45, 56, 67, 78, 89, 90}
var b []int = a[1:5]  //创建一个切片 从 a[1] - a[4]
fmt.Println(b)
}
``````

`a[1:5]`创建了一个从`a[1] - a[4]`的切片。切片b的值为：`[56 67 78 89]`

``````package main

import "fmt"

func main(){
c := []int{6, 7, 8}  //创建一个数组 c ,并返回一个存储在 c 中的切片引用
fmt.Println(c)
}
``````

# 修改切片

``````package main

import "fmt"

func main(){
num := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9}   //定义数组 num
snum := num[2:8]   //创建切片从 num[2] - num[7]
fmt.Println("before change", num)   //输出改变前
for i := range snum {
snum[i]++  //给切片每个参数+1
}
fmt.Println("after change", num)   //输出改变后
}
``````

before change [1 2 3 4 5 6 7 8 9]
after change [1 2 4 5 6 7 8 9 9]

# 切片的长度和容量

slice的长度对应slice中的元素数量；长度不能超过容量。容量一般是从slice的开始为止到底层数组的结束位置。

``````package main

import "fmt"

func main(){
/*一个数组的第一个索引是从0开始，若想跳过0，则用1:的方式，第0个元素会自动初始化为空字符串*/
months := [...]string{1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"}
Q2 := months[4:7]  //第二季度
summer := months[6:9]   //夏天

fmt.Printf("length of Q2 is %d, capacity is %d\n", len(Q2), cap(Q2))
fmt.Printf("length of summer is %d, capacity is %d", len(summer), cap(summer))
}
``````

length of Q2 is 3, capacity is 9
length of summer is 3, capacity is 7

``````fmt.Println(summer[:20])   //报错panic:runtime error: slice bounds out of range
``````
``````package main

import "fmt"

func main(){
/*一个数组的第一个索引是从0开始，若想跳过0，则用1:的方式，第0个元素会自动初始化为空字符串*/
months := [...]string{1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec"}
Q2 := months[4:7]  //第二季度
summer := months[6:9]   //夏天

//fmt.Printf("length of Q2 %d, capacity %d\n", len(Q2), cap(Q2))
//fmt.Printf("length of summer %d, capacity %d", len(summer), cap(summer))

//fmt.Println(summer[:20])  //报错panic:runtime error: slice bounds out of range

endlessSummer := summer[:5]  //扩展summer长度，并给切片endlessSummer
fmt.Println(endlessSummer)
fmt.Printf("the length os endlessSummer is %d, capacity is %d", len(endlessSummer), cap(endlessSummer))
}
``````

the length os endlessSummer is 5, capacity is 7

# 使用make创建切片

`func make（[]T，len，cap）`[]T 通过传递类型，长度和容量来创建切片。容量是可选参数, 默认值为切片长度。make 函数创建一个数组，并返回引用该数组的切片。

``````package main

import (
"fmt"
)

func main() {
i := make([]int, 5, 5)  //引用make函数创建切片
fmt.Println(i)
}
``````

# 追加切片元素

x ... T 在函数定义中表示该函数接受参数 x 的个数是可变的。这些类型的函数被称为可变函数。

``````package main

import "fmt"

func main(){
cars := []string{"Ferrari", "Honda", "Ford"}  //定义切片cars
fmt.Println(cars)
fmt.Println("old cars length is ", len(cars), "and capacity is ", cap(cars))  //输出cars的长度和容量
newcars := append(cars, "BYD")   //cars 切片增加新元素并定义给另一个切片newcars
fmt.Println(newcars)
fmt.Println("new cars length is ", len(newcars), "and capacity is ", cap(newcars))  //输出newcars长度和容量

}
``````

[Ferrari Honda Ford]
old cars length is 3 and capacity is 3
[Ferrari Honda Ford BYD]
new cars length is 4 and capacity is 6

# 多维切片

``````package main

import "fmt"

func main(){
/*多维数组*/
pls := [][]string {
{"C", "C++"},
{"JavaScript"},
{"Go", "Rust"},
}
for _, v1 := range pls {
for _, v2 := range v1 {
fmt.Printf("%s ", v2)
}
fmt.Printf("\n")
}
}
``````

C C++
JavaScript
Go Rust