欢迎来到 Golang 系列教程,在本教程中我们讨论Go的数组和切片
文章目录
数组
数组是属于相同类型的元素的集合。例如,整型集合 5,8,9,79 形成一个数组,不同类型的混合值,例如同时包含字符串和整型的数组,在Go中是不允许的。
声明
数组属于 T[n]
类型。n
代表数组中元素的个数,T
代表每个元素的类型。元素的个数 n
也是类型的一部分(我们将在稍后更详细地讨论这个问题)。
声明数组有不同的方式。我们来一个一个地看它们。
package main
import (
"fmt"
)
func main() {
var a [3]int //int array with length 3
fmt.Println(a)
}
var a [3]int声明一个长度为 3 的数组。数组中所有的元素自动地被赋予数组类型的零值。在这个例子中 a
是一个整型数组类型,因此 a
中所有的元素被赋予 0
,int 类型的零值。运行上面的程序将 打印 [0 0 0]
。
数组的索引从 0
开始,以 length - 1
结束。我们来为上面数组赋予一些值。
package main
import (
"fmt"
)
func main() {
var a [3]int //int array with length 3
a[0] = 12 // array index starts at 0
a[1] = 78
a[2] = 50
fmt.Println(a)
}
a[0] 为数组的第一个元素赋值。程序会打印[17 78 50]
我们来使用简短声明创建同样的数组。
package main
import (
"fmt"
)
func main() {
a := [3]int{12, 78, 50} // short hand declaration to create array
fmt.Println(a)
}
上面的程序同样打印 [12 78 50]
在简短的声明时,没有必要为数组中所有的元素都指定一个值。
package main
import (
"fmt"
)
func main() {
a := [3]int{12}
fmt.Println(a)
}
上面程序在第 8 行 a := [3]int{12}
声明一个长度为 3 的数组,但是它仅提供一个值 12
。剩下的 2 个元素被自动赋值为 0
。这个程序会打印 [12 0 0]
。
你甚至可以在声明时忽略数组的长度,使用 ...
代替。让编译器为你找出长度。这通过下面的程序完成。
package main
import (
"fmt"
)
func main() {
a := [...]int{12, 78, 50} // ... makes the compiler determine the length
fmt.Println(a)
}
数组的大小是类型的一部分。因此 [5]int
和 [25]int
是不同的类型。由于这个原因,数组不可以调整大小。不要担心这个限制,因为 slice
的存在克服了它。
package main
func main() {
a := [3]int{5, 78, 8}
var b [5]int
b = a //not possible since [3]int and [5]int are distinct types
}
上面程序的第 6 行,我们试图向类型为[3]int
的变量赋值给类型为 [5]int
的变量,这是不被允许的,因此编译器将抛出 main.go:6:cannot use a (type [3]int) as type [5]int in assignment 的错误。
数组是值类型
Go中的数组是值类型而不是引用类型。这意味着当它们被赋值给一个新的变量,源数组的一个副本被赋值给新的变量。如果修改新的变量,它将不会影响源数组。
package main
import "fmt"
func main() {
a := [...]string{"USA", "China", "India", "Germany", "France"}
b := a // a copy of a is assigned to b
b[0] = "Singapore"
fmt.Println("a is ", a)
fmt.Println("b is ", b)
}
上面程序的第 7 行,a
的一个副本被赋值给b
。在第 8 行,b
的第一个元素被修改为 Singapore
。这将不会影响源数组a
。程序会输出
a is [USA China India Germany France]
b is [Singapore China India Germany France]
类似地,当数组作为参数传递给函数,他们是值传递,源数组不会改变。
package main
import "fmt"
func changeLocal(num [5]int) {
num[0] = 55
fmt.Println("inside function ", num)
}
func main() {
num := [...]int{5, 6, 7, 8, 8}
fmt.Println("before passing to function ", num)
changeLocal(num) //num is passed by value
fmt.Println("after passing to function ", num)
}
上面程序的第 13 行。数组 num
实际上被值传递给函数 changeLocal
,因此不会由于函数的调用被修改。程序会打印
before passing to function [5 6 7 8 8]
inside function [55 6 7 8 8]
after passing to function [5 6 7 8 8]
数组的长度
数组的长度可以通过作为参数传递给 len
函数被发现。
package main
import "fmt"
func main() {
a := [...]float64{67.7, 89.8, 21, 78}
fmt.Println("length of a is",len(a))
}
上面程序的输出是 length of a is 4
。
使用 range 迭代数组
for
循环可以被用来迭代一个数组的元素
package main
import "fmt"
func main() {
a := [...]float64{67.7, 89.8, 21, 78}
for i := 0; i < len(a); i++ { //looping from 0 to the length of the array
fmt.Printf("%d th element of a is %.2f\n", i, a[i])
}
}
上面程序使用一个 for
循环来迭代数组元素,从索引 0
到 length of the array - 1
。这个程序打印
0 th element of a is 67.70
1 th element of a is 89.80
2 th element of a is 21.00
3 th element of a is 78.00
Go提供一个更好和简单的方法来迭代数组,即使用 range 格式的 for
循环。range
返回索引和该索引对应的值。我们使用 range 重写上面的代码。我们也要计算数组所有元素的和。
package main
import "fmt"
func main() {
a := [...]float64{67.7, 89.8, 21, 78}
sum := float64(0)
for i, v := range a {//range returns both the index and value
fmt.Printf("%d the element of a is %.2f\n", i, v)
sum += v
}
fmt.Println("\nsum of all elements of a",sum)
}
在上面程序的第 8 行,for i, v := range a
是range格式的 for 循环。它同时返回索引和该索引处的值。我们打印该值并计算 数组 a
所有元素的和。程序打印
0 the element of a is 67.70
1 the element of a is 89.80
2 the element of a is 21.00
3 the element of a is 78.00
sum of all elements of a 256.5
如果你仅需要值而希望忽略索引,你可以使用 _
空格标示符代表索引
for _, v := range a { // ignores indes
}
上面的 for 循环忽略索引。类似地值也可以被忽略。
多维数组
目前我们所创建的数组都是一维的。可以创建多维数组。
package main
import (
"fmt"
)
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[1][1] = "google"
b[2][0] = "AT&T"
b[2][1] = "T-Mobile"
fmt.Printf("\n")
printarray(b)
}
上面程序的第 17 行,使用简短的语法声明一个二维字符串数组 a
。在 20 行结尾的逗号是必要的。这是因为词法分析器根据简单的规则自动插入分号。如果你想了解更多为什么这是必要的,请阅读https://golang.org/doc/effective_go.html#semicolons
第 7 行的 printarray
函数使用两个 for range 循环来打印第 2 组数组的内容。程序输出
lion tiger
cat dog
pigeon peacock
apple samsung
microsoft google
AT&T T-Mobile
这些就是数据。尽管数组看上去足够灵活,但是它们有固定长度的限制。不能够增加数组的长度。所以 slice出现了。其实在Go中。slices 比数组更常见。
Slices
数组是方便的,灵活的和比 数组更有力量的武器。切片本身并不拥有任何数据。它仅仅是存在的数组的索引。
创建切片(slice)
元素类型为 T 的代表使用 []T
来表示。
package main
import (
"fmt"
)
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)
}
语法 a[start:end]
从数组 a
的开始索引 start
到索引 end-1
创建一个切片。所以在上面程序的第 9 行,a[1:4]
创建一个表示数组 a
索引 1 到 3 的切片。因此切片 b
的值是 [77 78 79]
。
看另一个创建切片的方法
package main
import (
"fmt"
)
func main() {
c := []int{6, 7, 8} //creates and array and returns a slice reference
fmt.Println(c)
}
在上面程序的第 9 行,`c := []int{6,7,8} 创建一个有 3 个整型元素的数组,并返回切片索引存储在 c 中。
修改切片
切片本身并不拥有任何数据,它仅仅是底层数组的一个代表。任何对该切片的修改将被反射到底层数组上。
package main
import (
"fmt"
)
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)
}
在上面程序的第 9 行,我们从数组的索引 2,3,4 创建一个 dslice
。for 循环将这索引的值增加 1 。当在 for 循环后打印数组,我们可以看到对切片的修改反射到数组上。程序的输出是
array before [57 89 90 82 100 78 67 69 59]
array after [57 89 91 83 101 78 67 69 59]
当许多切片共享相同的底层数组时,每个切片所做的更改将反映在数组中。
package main
import (
"fmt"
)
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)
}
在第 8 行,在 num[:]
中,开始和结尾值是消失了。开始和结束的默认值分别是 0
和 len(numa)
。切片 nums1
和 nums2
共享同一个数组。程序的输出是
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]
从输出中,很明显当切片共享相同的数组时,每个切片的修改都反射到数组上。
切片的长度和容量
切片的长度是切片的元素个数。切片的容量是从创建切片的索引开始的底层数组中的元素数。
我们来写一些代码来更好地理解它。
package main
import (
"fmt"
)
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
}
上面程序中,fruitslice
从 fruitearray
的索引 1 和 2 被创建。因此 fruitslice
的长度为 2。
fruitarray
的长度是 7。fruiteslice
从 fruitarray
的索引 1
被创建。因此 fruitslice
的容量是从索引 1
开始的 fruitarray
中的元素,即 orange
,该值是 6
。因此 fruitslice
的容量是 6。这个程序输出 length of slice 2 capacity 6
切片可以被重切处到它的容易。任何超出容易将会导致程序抛出运行时错误
package main
import (
"fmt"
)
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\n", len(fruitslice), cap(fruitslice)) //length of is 2 and capacity is 6
fruitslice = fruitslice[:cap(fruitslice)] //re-slicing furitslice till its capacity
fmt.Println("After re-slicing length is",len(fruitslice), "and capacity is",cap(fruitslice))
}
在上面程序的第 11 行,fruitslice
被重切片到它的容易。上面程序输出
length of slice 2 capacity 6
After re-slicing length is 6 and capacity is 6
使用make创建切片
func make([]T,len,cap) []T可以通过传递 type, length 和 capacity 被用来创建一个切片。capacity 参数是可选的,默认是长度。make 函数创建一个数组返回一个指向它的切片。
package main
import (
"fmt"
)
func main() {
i := make([]int, 5, 5)
fmt.Println(i)
}
当使用 make 创建一个切片时,默认值是零值。上面程序输出 [0 0 0 0 0]
。
附加到切片
正如我们已经知道的,数组被限定到固定长度,他们的长度不可以被增加。切片是动态的,新元素可以使用 append
函数附加到切片。附加函数的定义是 func append(s []T, x ...T) []T
。
函数定义中的 x …T 意味着函数参数 x 接受可变数目的参数。这些函数的类型被称为 变参函数。
但有一个问题可能会困扰你。如果切片的底层是数组,数组本身是固定长度的,那切片的长度是如何动态的。当新的元素被附加到切片,底层会发生什么?一个新的数组被创建。已经存在的数组元素被拷贝到新的数组中,并为新的数组返回一个新的切片引用。新切片的容量是旧切片的两倍。很酷吧。下面的程序将使事情更清晰。
package main
import (
"fmt"
)
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
的初始容量是 3〈〉我们在第 10 行为 cars 附加一个新的元素。通过 append(cars, "Toyota")
返回切片再次赋值给 cars。现在 cars 的容量增加了一倍 ,是6。上面程序的输出是
cars: [Ferrari Honda Ford] has old length 3 and capacity 3
cars: [Ferrari Honda Ford Toyota] has new length 4 and capacity 6
切片类型的零值是 nil
。nil
的切片的长度和容量都是 0。可以使用 append 函数给 nil
切片附加值。
package main
import (
"fmt"
)
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)
}
}
在上面程序中,names
是空的,我们向 names
append 3 个字符串。程序的输出是
slice is nil going to append
names contents: [John Sebastian Vinay]
也可以使用 ...
操作符将一个切片附加给另一个切片。你可以在教程变参函数学习更多关于这个操作符的内容。
package main
import (
"fmt"
)
func main() {
veggies := []string{"potatoes","tomatoes","brinjal"}
fruits := []string{"oranges","apples"}
food := append(veggies, fruits...)
fmt.Println("food:",food)
}
在上面程序的第 10 行,food
通过将 fruits
附加给 veggies
被创建。程序的输出为 food: [potatoes tomatoes brinjal organes apples]
。
将 slice 传递给函数
切片可以被认为是由结构类型在内部表示。这是它的样子,
type slice struct {
Length int
Capacity int
ZerothElement *byte
}
切片包含 length,capacity 和一个指向数组第0个元素的指针。当切片被传递给函数,即使它是通过值传递的,指针变量将指向同样的底层数组。因此当切片作为参数传递给函数,在函数内部修改对于函数外部是可见的。
package main
import (
"fmt"
)
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
}
上面程序的第 17 行的函数调用,将切片的每个元素减少 2。当切片在函数调用之后打印,这些改变是可见的。如果你能想起的话,这和数组是不同的,数组在函数内部修改对于函数外是不可见的。上面程序输出
slice before function call [8 7 6]
slice after function call [6 5 4]
多维切片
和数组类似,切片也有多维。
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
内存优化
切片拥有底层数组的指针。只要切片在内存中,数组就不能够被垃圾回收。在内存管理方面,这点是需要注意的。我们假设有一个非常大的数组,我们只对处理它的一小部分感兴趣。今后,我们从该数组上创建切片,并开始处理这个切片。这儿需要注意的重要的事情是,由于切片引用它,数组一直待在内存中。
解决这个问题的一个方法是使用copy函数 func copy(dst, src []T) int
创建一个切片的副本。这个方法我们可以使用新的切片,旧的切片可以被垃圾回收。
package main
import (
"fmt"
)
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)
}
在上面程序的第 9 行,neededCountries := countries[:len(countries)-2]
创建一个 countries
的不含最后两个元素的切片。在程序的第 11 行将 neededCountries
拷贝给 contriesCpy
,并在下面的一行从函数中的返回它。现在 countries
数组可以被垃圾回收,由于 neededCountries
现在不再引用它。
我已经编译了我们目前为止所讨论的所有概念到一个程序的,你可以从github下载它。
下一教程 - 变参函数