# DAY6 GOLANG （六） 数组与切片

· · 146 次点击 · · 开始浏览

### 数组的定义

var 数组名 [ 数组大小]数据类型
var a [5]int

### 四种初始化数组的方式

var numArr01 [3]int =[3]int{1, 2, 3}
var numArr02 = [3]int{5, 6, 7}
//这里的 [...]是规定的写法
var numArr03 = [...]int{8， 9 ，10}
var numArr04 = [...]int{1: 800, 0: 900, 2:999}

### 数组的遍历

#### 1.普通方式遍历

func main() {
a := [...]float64{67.7, 89.8, 21, 78}
for i := 0; i < len(a); i++ {
fmt.Printf("%d th element of a is %.2f\n", i, a[i])
}
}

#### 2.for-range 结构遍历

func main() {
a := [...]float64{67.7, 89.8, 21, 78}
for i, v := range a {
fmt.Printf("%d the element of a is %.2f\n", i, v)
}
}

range 返回数组的索引和索引对应的值

### 多维数组

func printarray(a [3][2]string) {
for _, v1 := range a {
for _, v2 := range v1 {
fmt.Printf("%s ", v2)
}
fmt.Printf("\n")
}
}

func main() {
a := [3][2]string{
{"lion", "tiger"},
{"cat", "dog"},
{"pigeon", "peacock"}, //this comma is necessary. The compiler will complain if you omit this comma
}
printarray(a)
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")
printarray(b)
}

lion tiger
cat dog
pigeon peacock

apple samsung
AT&T T-Mobile

for index ，value ：= range arry01{
}
index 返回的是数组的下标，value是该下标对应的值。

### 切片

#### 方式一

func main() {
a := [5]int{76, 77, 78, 79, 80}
var b []int = a[1:4] //creates a slice from a[1] to a[3]
fmt.Println(b)
}

#### 方式二

func main() {
c := []int{6, 7, 8} //creates and array and returns a slice reference
fmt.Println(c)
}

### 修改切片

func main() {
darr := [...]int{57, 89, 90, 82, 100, 78, 67, 69, 59}
dslice := darr[2:5]
fmt.Println("array before",darr)
for i := range dslice {
dslice[i]++
}
fmt.Println("array after",darr)
}

array before [57 89 90 82 100 78 67 69 59]
array after [57 89 91 83 101 78 67 69 59]

func main() {
numa := [3]int{78, 79 ,80}
nums1 := numa[:] //creates a slice which contains all elements of the array
nums2 := numa[:]
fmt.Println("array before change 1",numa)
nums1[0] = 100
fmt.Println("array after modification to slice nums1", numa)
nums2[1] = 101
fmt.Println("array after modification to slice nums2", numa)
}

array before change 1 [78 79 80]
array after modification to slice nums1 [100 79 80]
array after modification to slice nums2 [100 101 80]

### 切片的长度和容量

func main() {
fruitarray := [...]string{"apple", "orange", "grape", "mango", "water melon", "pine apple", "chikoo"}
fruitslice := fruitarray[1:3]
fmt.Printf("length of slice %d capacity %d", len(fruitslice), cap(fruitslice)) //length of is 2 and capacity is 6
}

func main() {
fruitarray := [...]string{"apple", "orange", "grape", "mango", "water melon", "pine apple", "chikoo"}
fruitslice := fruitarray[1:3]
fmt.Printf("length of slice %d capacity %d", len(fruitslice), cap(fruitslice)) //length of is 2 and capacity is 6
}

fruitarray 的长度是 7。fruiteslice 是从 fruitarray 的索引 1 开始的。因此 fruiteslice 的容量是从 fruitarray 的第 1 个元素开始算起的数组中的元素个数，这个值是 6。因此 fruitslice 的容量是 6。程序的输出为：length of slice 2 capacity 6。

### 用make创建切片

func main() {
i := make([]int, 5, 5)
fmt.Println(i)
}

make 创建的切片的元素值默认为 0 值。上面的程序输出为：[0 0 0 0 0]

### 追加元素到切片

x …T 表示 append 函数可以接受的参数个数是可变的。这种函数叫做变参函数

func main() {
cars := []string{"Ferrari", "Honda", "Ford"}
fmt.Println("cars:", cars, "has old length", len(cars), "and capacity", cap(cars)) //capacity of cars is 3
cars = append(cars, "Toyota")
fmt.Println("cars:", cars, "has new length", len(cars), "and capacity", cap(cars)) //capacity of cars is doubled to 6
}

cars: [Ferrari Honda Ford] has old length 3 and capacity 3
cars: [Ferrari Honda Ford Toyota] has new length 4 and capacity 6

func main() {
var names []string //zero value of a slice is nil
if names == nil {
fmt.Println("slice is nil going to append")
names = append(names, "John", "Sebastian", "Vinay")
fmt.Println("names contents:",names)
}
}

slice is nil going to append
names contents: [John Sebastian Vinay]

func main() {
veggies := []string{"potatoes","tomatoes","brinjal"}
fruits := []string{"oranges","apples"}
food := append(veggies, fruits...)
fmt.Println("food:",food)
}

### 切片作为函数参数

type slice struct {
Length        int
Capacity      int
ZerothElement *byte
}

func subtactOne(numbers []int) {
for i := range numbers {
numbers[i] -= 2
}

}
func main() {

nos := []int{8, 7, 6}
fmt.Println("slice before function call", nos)
subtactOne(nos)                               //function modifies the slice
fmt.Println("slice after function call", nos) //modifications are visible outside

}

array before function call [8 7 6]
array after function call [6 5 4]

### 多维切片

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

### 内存优化

func countries() []string {
countries := []string{"USA", "Singapore", "Germany", "India", "Australia"}
neededCountries := countries[:len(countries)-2]
countriesCpy := make([]string, len(neededCountries))
copy(countriesCpy, neededCountries) //copies neededCountries to countriesCpy
return countriesCpy
}
func main() {
countriesNeeded := countries()
fmt.Println(countriesNeeded)
}

• 定义：var arr [4] [6]int ---------------------[[0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0 0]]

赋值 : arr [2] [9]= 3

遍历一次的话就是遍历出里面的数组

要是想遍历出所有的元素要进行嵌套循环

直接赋值： var 数组名 【大小】 【大小】类型=【大小】 【大小】类型{{初值。。。}{初值。。。。}}

arr := 【】【】int {{123}{356}}

• 二维数组的遍历

• for ---- range

for i , v := range arr{----------- v 是一个一维数组

for j , v1 := range v{

..............................................

}

}

• 双重for循环：

for i:=0;i<len(arr);i++{

for j:=0;j<len (arr[ i ]);j++{

................................................

}

}

0 回复

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

### 数组的定义

var 数组名 [ 数组大小]数据类型
var a [5]int

### 四种初始化数组的方式

var numArr01 [3]int =[3]int{1, 2, 3}
var numArr02 = [3]int{5, 6, 7}
//这里的 [...]是规定的写法
var numArr03 = [...]int{8， 9 ，10}
var numArr04 = [...]int{1: 800, 0: 900, 2:999}

### 数组的遍历

#### 1.普通方式遍历

func main() {
a := [...]float64{67.7, 89.8, 21, 78}
for i := 0; i < len(a); i++ {
fmt.Printf("%d th element of a is %.2f\n", i, a[i])
}
}

#### 2.for-range 结构遍历

func main() {
a := [...]float64{67.7, 89.8, 21, 78}
for i, v := range a {
fmt.Printf("%d the element of a is %.2f\n", i, v)
}
}

range 返回数组的索引和索引对应的值

### 多维数组

func printarray(a [3][2]string) {
for _, v1 := range a {
for _, v2 := range v1 {
fmt.Printf("%s ", v2)
}
fmt.Printf("\n")
}
}

func main() {
a := [3][2]string{
{"lion", "tiger"},
{"cat", "dog"},
{"pigeon", "peacock"}, //this comma is necessary. The compiler will complain if you omit this comma
}
printarray(a)
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")
printarray(b)
}

lion tiger
cat dog
pigeon peacock

apple samsung
AT&T T-Mobile

for index ，value ：= range arry01{
}
index 返回的是数组的下标，value是该下标对应的值。

### 切片

#### 方式一

func main() {
a := [5]int{76, 77, 78, 79, 80}
var b []int = a[1:4] //creates a slice from a[1] to a[3]
fmt.Println(b)
}

#### 方式二

func main() {
c := []int{6, 7, 8} //creates and array and returns a slice reference
fmt.Println(c)
}

### 修改切片

func main() {
darr := [...]int{57, 89, 90, 82, 100, 78, 67, 69, 59}
dslice := darr[2:5]
fmt.Println("array before",darr)
for i := range dslice {
dslice[i]++
}
fmt.Println("array after",darr)
}

array before [57 89 90 82 100 78 67 69 59]
array after [57 89 91 83 101 78 67 69 59]

func main() {
numa := [3]int{78, 79 ,80}
nums1 := numa[:] //creates a slice which contains all elements of the array
nums2 := numa[:]
fmt.Println("array before change 1",numa)
nums1[0] = 100
fmt.Println("array after modification to slice nums1", numa)
nums2[1] = 101
fmt.Println("array after modification to slice nums2", numa)
}

array before change 1 [78 79 80]
array after modification to slice nums1 [100 79 80]
array after modification to slice nums2 [100 101 80]

### 切片的长度和容量

func main() {
fruitarray := [...]string{"apple", "orange", "grape", "mango", "water melon", "pine apple", "chikoo"}
fruitslice := fruitarray[1:3]
fmt.Printf("length of slice %d capacity %d", len(fruitslice), cap(fruitslice)) //length of is 2 and capacity is 6
}

func main() {
fruitarray := [...]string{"apple", "orange", "grape", "mango", "water melon", "pine apple", "chikoo"}
fruitslice := fruitarray[1:3]
fmt.Printf("length of slice %d capacity %d", len(fruitslice), cap(fruitslice)) //length of is 2 and capacity is 6
}

fruitarray 的长度是 7。fruiteslice 是从 fruitarray 的索引 1 开始的。因此 fruiteslice 的容量是从 fruitarray 的第 1 个元素开始算起的数组中的元素个数，这个值是 6。因此 fruitslice 的容量是 6。程序的输出为：length of slice 2 capacity 6。

### 用make创建切片

func main() {
i := make([]int, 5, 5)
fmt.Println(i)
}

make 创建的切片的元素值默认为 0 值。上面的程序输出为：[0 0 0 0 0]

### 追加元素到切片

x …T 表示 append 函数可以接受的参数个数是可变的。这种函数叫做变参函数

func main() {
cars := []string{"Ferrari", "Honda", "Ford"}
fmt.Println("cars:", cars, "has old length", len(cars), "and capacity", cap(cars)) //capacity of cars is 3
cars = append(cars, "Toyota")
fmt.Println("cars:", cars, "has new length", len(cars), "and capacity", cap(cars)) //capacity of cars is doubled to 6
}

cars: [Ferrari Honda Ford] has old length 3 and capacity 3
cars: [Ferrari Honda Ford Toyota] has new length 4 and capacity 6

func main() {
var names []string //zero value of a slice is nil
if names == nil {
fmt.Println("slice is nil going to append")
names = append(names, "John", "Sebastian", "Vinay")
fmt.Println("names contents:",names)
}
}

slice is nil going to append
names contents: [John Sebastian Vinay]

func main() {
veggies := []string{"potatoes","tomatoes","brinjal"}
fruits := []string{"oranges","apples"}
food := append(veggies, fruits...)
fmt.Println("food:",food)
}

### 切片作为函数参数

type slice struct {
Length        int
Capacity      int
ZerothElement *byte
}

func subtactOne(numbers []int) {
for i := range numbers {
numbers[i] -= 2
}

}
func main() {

nos := []int{8, 7, 6}
fmt.Println("slice before function call", nos)
subtactOne(nos)                               //function modifies the slice
fmt.Println("slice after function call", nos) //modifications are visible outside

}

array before function call [8 7 6]
array after function call [6 5 4]

### 多维切片

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

### 内存优化

func countries() []string {
countries := []string{"USA", "Singapore", "Germany", "India", "Australia"}
neededCountries := countries[:len(countries)-2]
countriesCpy := make([]string, len(neededCountries))
copy(countriesCpy, neededCountries) //copies neededCountries to countriesCpy
return countriesCpy
}
func main() {
countriesNeeded := countries()
fmt.Println(countriesNeeded)
}

• 定义：var arr [4] [6]int ---------------------[[0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0 0]]

赋值 : arr [2] [9]= 3

遍历一次的话就是遍历出里面的数组

要是想遍历出所有的元素要进行嵌套循环

直接赋值： var 数组名 【大小】 【大小】类型=【大小】 【大小】类型{{初值。。。}{初值。。。。}}

arr := 【】【】int {{123}{356}}

• 二维数组的遍历

• for ---- range

for i , v := range arr{----------- v 是一个一维数组

for j , v1 := range v{

..............................................

}

}

• 双重for循环：

for i:=0;i<len(arr);i++{

for j:=0;j<len (arr[ i ]);j++{

................................................

}

}