本文已收录如何疾速学习Go的struct数据类型。涵盖PHP、JavaScript、Linux、Golang、MySQL、Redis和开源工具等等相干内容。
什么是数组
数组是属于同一类型的元素的汇合。例如,整数 5、8、9、79、76 的汇合造成一个数组。Go 中不容许混合不同类型的值,例如,同时蕴含字符串和整数的数组。
申明数组
数组属于类型 。 示意数组中的元素数,并示意每个元素的类型。元素的数量也是类型的一部分(咱们稍后将对此进行更具体的探讨。[n]TnTn
有不同的办法来申明数组。让咱们一个接一个地看一下。
package mainimport ( "fmt")func main() { var a [3]int //int array with length 3 fmt.Println(a)}
var a [3]int 申明一个长度为 3 的整数数组。数组中的所有元素都将主动调配数组类型的零值。在这种状况下是一个整数数组,因而的所有元素都赋给 ,int 的零值。运行上述程序将打印a a 0
[0 0 0]
数组的索引从 开始,到 完结于 。让咱们为下面的数组调配一些值。0 length - 1。
package mainimport ( "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] 将值赋给数组的第一个元素。该程序将打印
[12 78 50]
让咱们应用短语法申明创立雷同的数组。
package main import ( "fmt")func main() { // short hand declaration to create array a := [3]int{12, 78, 50} fmt.Println(a)}
下面的程序将打印雷同的输入:
[12 78 50]
在短语法申明期间,不用为数组中的所有元素赋值。
package mainimport ( "fmt")func main() { a := [3]int{12} fmt.Println(a)}
在下面的程序中,第 8 行申明了一个长度为 3 的数组,但只提供了一个值 。其余 2 个元素将主动指定。此程序将打印a := [3]int{12} 12 0
[12 0 0]
您甚至能够疏忽申明中数组的长度,并将其替换为,并让编译器为您找到长度。这是在以下程序中实现的。...
package mainimport ( "fmt")func main() { // ... makes the compiler determine the length a := [...]int{12, 78, 50} fmt.Println(a)}
数组的大小是类型的一部分。因而 和 是不同的类型。因而,无奈调整数组的大小。
package mainfunc 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 行中,咱们尝试将类型的变量调配给不容许的类型变量,因而编译器将打印以下谬误:
./prog.go:6:7: cannot use a (type [3]int) as type [5]int in assignment
数组是值类型
Go 中的数组是值类型,而不是援用类型。这意味着,当它们被调配给新变量时,原始数组的正本将调配给新变量。如果对新变量进行了更改,它将不会反映在原始数组中。
package mainimport "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) }
上述代码将打印出如下内容:
a is [USA China India Germany France] b is [Singapore China India Germany France]
同样,当数组作为参数传递给函数时,它们按值传递,原始数组放弃不变。
package mainimport "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 行程序中,数组实际上是按值传递给函数的,因而不会因为函数调用而更改。该程序将打印:
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 mainimport "fmt"func main() { a := [...]float64{67.7, 89.8, 21, 78} fmt.Println("length of a is",len(a))}
上述程序将打印:
length of a is 4
迭代数组
应用for可用于循环拜访数组的元素。
package mainimport "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]) }}
下面的程序应用循环来迭代数组的元素,从 index 到 。该程序无效并将打印:
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 提供了一种更好、更简洁的形式,通过应用循环的范畴模式来迭代数组。 返回索引和该索引处的值。让咱们应用范畴重写下面的代码。咱们还将找到数组中所有元素的总和。
package mainimport "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 循环的范畴模式。它将返回索引和该索引处的值。咱们打印值,并计算数组中所有元素的总和。该程序的输入是:
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.00sum of all elements of a 256.5
如果您只想要该值并心愿疏忽索引,则能够通过将索引替换为空白标识符来执行此操作。_
for _, v := range a { //ignores index }
下面的 for 循环疏忽了索引。同样,该值也能够疏忽。
多维数组
到目前为止,咱们创立的数组都是单维的。能够创立多维数组。
package mainimport ( "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 行中,应用短手语法申明了一个二维字符串数组。第 20 行开端的逗号是必须的。这是因为词法分析器依据简略规定主动插入分号。如果您有趣味理解无关为什么须要分号的更多信息,请浏览参考文章。另一个 2d 数组在第 23 行中申明,并为每个索引一一增加字符串。这是初始化 2d 数组的另一种办法。
第 7 行中的函数应用两个 for 范畴循环来打印 2d 数组的内容。以上程序将打印:
lion tiger cat dog pigeon peacock apple samsung microsoft google AT&T T-Mobile
数组就是这样。只管数组仿佛足够灵便,但它们具备固定长度的限度。不能减少数组的长度。这就是切片进入画面的中央。事实上,在 Go 中,切片比传统数组更常见。
切片
切片是数组顶部的不便、灵便且功能强大的包装器。切片自身不领有任何数据。它们只是对现有数组的援用。
创立切片
具备 T 类型元素的切片由下式示意[]T
。
package mainimport ( "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)}
该语法从一个数组开始从一个索引到另一个索引创立一个切片。因而,在下面程序的第 9 行中,从索引 1 到 3 创立数组的切片示意模式。应用该表达式:a[start:end]
。
package mainimport ( "fmt")func main() { //creates and array and returns a slice reference c := []int{6, 7, 8} fmt.Println(c)}
在下面的函数的第 9 行中,创立一个蕴含 3 个整数的数组,并返回存储在 c 中的切片援用。
批改切片
切片不领有本人的任何数据。它只是根底数组的示意模式。对切片所做的任何批改都将反映在根底数组中。
package mainimport ( "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 创立。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 mainimport ( "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)}
在第 9 行中,短少开始值和完结值。“开始”和“完结”的默认值别离为 和 。两个切片并共享同一个数组。程序的输入是:
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 mainimport ( "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 fruitslice is 2 and capacity is 6}
在下面的程序中,是从 的索引 1 和 2 创立的。因而,的长度为 2。
切片能够从新切片到其容量。超出此值的任何内容都将导致程序引发运行时谬误。
package mainimport ( "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行中,被从新切片到其容量。以上程序输入:
length of slice 2 capacity 6 After re-slicing length is 6 and capacity is 6
应用make创立切片
生成切片能够应用make([]T, len, cap)来创立切片。[]T示意数据类型、len示意切片长度、cap示意切片容量。make 函数创立一个数组并返回对它的切片援用。
package mainimport ( "fmt")func main() { i := make([]int, 5, 5) fmt.Println(i)}
默认状况下,应用 make 创立切片时,这些值将清零。上述程序将输入 。[0 0 0 0 0]
切片追加
正如咱们曾经晓得的那样,数组被限度为固定长度,并且它们的长度不能减少。切片是动静的,能够应用函数将新元素追加到切片中。追加函数的定义是 。append([]T, x...):[]T
。返回的是一个新的切片。
x ...函数定义中的 T 示意函数承受参数 x 的可变数量的参数。这些类型的函数称为可变参数函数。
不过,有一个问题可能会困扰您。如果切片由数组反对,并且数组自身具备固定长度,那么切片如何具备动静长度。在引擎盖下产生的事件是,当新元素追加到切片时,将创立一个新数组。现有数组的元素将复制到此新数组,并返回此新数组的新切片援用。新切片的容量当初是旧切片的两倍。以下程序将使事件变得清晰。
package mainimport ( "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}
在下面的程序中,容量最后为 3。咱们将新元素附加到第 10 行中的汽车,并将 返回的切片再次调配给汽车。当初,汽车的容量翻了一番,变成了6辆。上述程序的输入是:
cars: [Ferrari Honda Ford] has old length 3 and capacity 3 cars: [Ferrari Honda Ford Toyota] has new length 4 and capacity 6
切片类型的零值为 。切片的长度和容量为 0。能够应用追加函数将值追加到切片。
package mainimport ( "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) }}
在下面的程序中为 nil,咱们已将 3 个字符串附加到 。程序的输入是:
slice is nil going to append names contents: [John Sebastian Vinay]
也能够应用运算符将一个切片追加到另一个切片。
package mainimport ( "fmt")func main() { veggies := []string{"potatoes","tomatoes","brinjal"} fruits := []string{"oranges","apples"} food := append(veggies, fruits...) fmt.Println("food:",food)}
在上述程序的第 10 行中,通过附加到切片中。程序的输入是:
fruitsveggiesfood: [potatoes tomatoes brinjal oranges apples]
切片作为函数参数
能够将切片视为由构造类型在外部示意。
type slice struct { Length int Capacity int ZerothElement *byte}
切片蕴含长度、容量和指向数组第零个元素的指针。将切片传递给函数时,即便它按值传递,指针变量也将援用雷同的根底数组。因而,当切片作为参数传递给函数时,在函数外部所做的更改在函数内部也是可见的。让咱们编写一个程序来检查一下。
package mainimport ( "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 mainimport ( "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 函数来复制该切片。这样,咱们能够应用新的切片,并且能够对原始数组进行垃圾回收。copy(dst, src []T):int
。
package mainimport ( "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 行中,创立一个禁止最初 2 个元素的切片。上述程序的第 11 行复制到下一行中的函数,并从中返回它。当初数组能够被垃圾回收,因为它不再被援用。