Go Series Tutorial--11. Arrays and slices

Source: Internet
Author: User
Tags types of functions variadic
This is a creation in Article, where the information may have evolved or changed. Welcome to the 11th chapter of [Golang Series Tutorial] (/SUBJECT/2). In this tutorial, we'll talk about arrays and slices in the Go language. # # Arrays are collections of elements of the same type. For example, an integer set of 5,8,9,79,76 forms an array. Mixing different types of elements, such as arrays containing strings and integers, is not allowed in the Go language. (Translator Note: Of course, if it is an array of type interface{}, can contain any type) # # # Array of declarations an array is represented as ' [n]t '. ' n ' represents the number of elements in the array, and ' T ' represents the type of each element. The number of elements ' n ' is also part of that type (we'll discuss this in more detail later). You can declare an array in a different way, let's see it one by one. "' Gopackage mainimport (" FMT ") func main () {var A [3]int//int array with length 3 fmt. Println (A)} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/ZVGH82U0EJ) **var a[3]int** declares an integer array of length 3. * * All elements in an array are automatically assigned a value of 0 for the arrays type. * * In this case, ' A ' is an integer array, so all elements of ' a ' are assigned a value of ' 0 ', which is the 0 value of the int type. Running the above program will * * OUTPUT * * ' [0 0 0] '. The index of the array ends with ' 0 ' starting at ' length-1 '. Let's assign a value to the array above. "' Gopackage mainimport (" FMT ") func main () {var A [3]int//int array with length 3 a[0] =//array index starts at 0 A[1] = a[2] = fmt. Println (A)} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/WF0UJ8SV39) a[0] assigns a value to the first element of the array. The program will * * OUTPUT * * ' [12 78 50] '. Let's create the same array using the * * Shorthand declaration * *. "' Gopackage mainimport (" FMT ") func main () {a: = [3]int{12, +, +}/ShoRT hand declaration to create array FMT. Println (A)} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/NKOV04ZGI6) above the program will print the same * * output * * ' [12 78 50] '. In a shorthand declaration, you do not need to assign values to all the elements in the array. "' Gopackage mainimport (" FMT ") func main () {a: = [3]int{12} fmt. Println (A)} "[Online Run Program] (https://play.golang.org/p/AdPH0kXRly) in the above program, line 8th ' A: = [3]int{12} ' declares an array of length 3, but only provides a value of ' 12 ', The remaining 2 elements are automatically assigned a value of ' 0 '. This program will * * OUTPUT * * ' [12 0 0] '. You can even ignore the length of the declared array and use ' ... ' instead, let the compiler automatically calculate the length for you, which is implemented in the following program. "' Gopackage mainimport (" FMT ") func main () {a: = [...] Int{12, makes, +/-compiler determine the length FMT. Println (A)} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/_FVMR6KGDH) * * The size of the array is part of the type * *. So ' [5]int ' and ' [25]int ' are different types. Arrays cannot be resized, do not worry about this limitation, because the presence of ' slices ' can solve this problem. "' Gopackage MainFunc Main () {a: = [3]int{5, 8} var b [5]int B = A//not possible since [3]int and [5]int is Distin] CT types} ' [Online Run Program] (Https://play.golang.org/p/kBdot3pXSB) in line 6th of the above program, we are trying to assign the variable of type ' [3]int ' to a variable of type ' [5]int ', which is not allowed, So the compiler throws an error Main.go:6: cannot use a (type [3]int) as type [5]int in assignment. # # # array is a value type the array in Go is a value type instead of a reference type. This means that when an array is assigned to a new variable, the variable gets a copy of the original array. If you make changes to a new variable, the original array is not affected. "' Gopackage mainimport" FMT "Func Main () {a: = [...] string{"USA", "China", "India", "Germany", "France"} B: = A//a copy of A are assigned to B b[0] = "Singapore" FMT. Println ("A is", a) fmt. Println ("B is", B)} "[Online Running program] (HTTPS://PLAY.GOLANG.ORG/P/-NCGK1MQPD) in line 7th of the above program, a copy of ' A ' is assigned to ' B '. In line 8th, the first element of ' B ' is changed to ' Singapore '. This is not reflected in the original array ' a '. The program will * * OUTPUT * *, ' A is [USA China India Germany France] B are [Singapore China India Germany France] ' Similarly, when arrays are passed as arguments to functions, they are by value Passed, while the original array remains unchanged. "Gopackage mainimport" FMT "func changelocal (num [5]int) {num[0] = fmt. PRINTLN ("Inside function", num)}func main () {num: = [...] Int{5, 6, 7, 8, 8} FMT. Println ("Before passing to function", num) changelocal (num)//num are passed by value FMT. Println ("After passing to function", num)} "[Running Program Online] (Https://play.golang.org/p/e3U75Q8eUZ) in the 13 line of the above program, array ' num ' is actually passed to the function ' changelocal ' by value, and the array does not change because of a function call. This program will output, ' BEfore passing to function [5 6 7 8 8]inside function [6 7 8 8]after passing to function [5 6 7 8 8] ' # # # array length by using an array as a parameter Number passed to the ' Len ' function, you can get the length of the array. "' Gopackage mainimport" FMT "Func Main () {a: = [...] float64{67.7, 89.8, a. Fmt. Println ("Length of A is", Len (A))} "[Online Run Program] (Https://play.golang.org/p/UrIeNlS0RN) above the program output as ' length of a is 4 '. # # # Use the range Iteration Algebra group ' for ' Loop to iterate through the elements in the array. "' Gopackage mainimport" FMT "Func Main () {a: = [...] float64{67.7, 89.8, +, 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]}} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/80EJSTACO6) The program above uses the ' for ' loop to iterate through the array element, from index ' 0 ' to ' length of the array-1 '. This program runs after printing out, ' 0th element of a is 67.70 1st element of A is 89.80 2nd element of A is 21.00 3rd element of A is 78.00 "Go provides a better, more concise way to iterate through an array by using the **range** method of the ' for ' Loop. ' Range ' returns the index and the value at that index. Let's rewrite the above code using range. We can also get the sum of all the elements in the array. "' Gopackage mainimport" FMT "Func Main () {a: = [...] float64{67.7, 89.8, +, () 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)} ' [Online Run Program] (https://play.golang.org/p/Ji6FRon36m) The 8th line of the above program ' for I, V: = Range A ' is using the For loop range method. It returns the index and the value at that index. We print these values and calculate the sum of all the elements in the array ' a '. The * * Output of the program is * *, "0 The element of a is 67.701 the element of a are 89.802 the element of a is 21.003 the element of A is 78.0 0sum of all elements of a 256.5 "if you only need a value and want to ignore the index, you can do so by replacing the index with the ' _ ' blank identifier. Gofor _, V: = range A {///Ignores index} ' for loop ignores indexes, and the same value can be ignored. # # # Multidimensional Arrays So far we've created arrays that are one-dimensional, and the Go language can create multidimensional arrays. ' Gopackage 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 would 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] = "T" b[2] [1] = "T-mobile" FMT. Printf ("\ n") PrintArray (b)} "[Online Run Program] (HTTPS://PLAY.GOLANG.ORG/P/INCHXI4YY8) declares a two-dimensional string array A with a shorthand syntax in line 17th of the above procedure. A comma at the end of line 20 is required. This is because the semicolon is automatically inserted according to the rules of the Go language. As to why this is necessary, if you want to learn more, please read [https://golang.org/doc/effective_go.html#semicolons] (https://golang.org/doc/effective_ go.html#semicolons). Another two-dimensional array, B, is declared in 23 rows, and the string is added one at a to each index. This is another way to initialize a two-dimensional array. The PrintArray function on line 7th uses two range loops to print the contents of a two-dimensional array. The * * Output of the above program is * * * ' lion tigercat dogpigeon peacockapple samsungmicrosoft googleat&t t-mobile ' is an array, although the array appears to be flexible enough, However, they have a fixed length limit and cannot increase the length of the array. This is going to use the * * section. In fact, slices are more common in Go than traditional arrays. # # Slice slices are a handy, flexible, and powerful wrapper (Wrapper) built from arrays. The slice itself does not have any data. They are just references to existing arrays. # # # Creates a slice of the slice with a T-type element represented by ' []t ' = ' ' Gopackage mainimport ("FMT") func main () {a: = [5]int{76, A, a, B, A, C} var []int = A[1:4]//Creates a slice from a[1] to a[3] FMT. Println (b)} "[Running Program Online] (Https://play.golang.org/p/Za6w5eubBB) using syntax ' A[starT:end] ' Creates a slice from ' a ' array index ' start ' to the end of ' end-1 '. Therefore, in line 9th of the above procedure, ' a[1:4 ' creates a slice representation of the ' a ' array from index 1 to 3. Therefore, the value of slice ' B ' is ' [77 78 79] '. Let's look at another way to create a slice. "' Gopackage mainimport (" FMT ") func main () {c: = []int{6, 7, 8}//creates and array and returns a slice reference FMT.P Rintln (c)} "[Online Run Program] (Https://play.golang.org/p/_Z97MgXavA) on line 9th of the above program, ' c:= [] int {6,7,8} ' creates an array of 3 integral elements and returns a stored in C The slice reference in the. The Modify slice of # # # slice does not own any data. It is just a representation of the underlying array. Any modifications you make to the slice are reflected in the underlying array. "' Gopackage mainimport (" FMT ") func main () {darr: = [...] int{57,----------------- PRINTLN ("Array Before", Darr) for I: = Range dslice {dslice[i]++} fmt. PRINTLN ("Array after", Darr)} ' [Online Run Program] (https://play.golang.org/p/6FinudNf1k) in line 9th of the above program, we create a slice based on the array index 2,3,4 ' Dslice '. The For loop increments the values in these indexes one by one. When we use the For loop to print the group, we can see that changes to the slices are reflected in the array. The output of this program is ' ' ' ' array before [all-in-one] array after [57 89 91 83 101 78 67 69 59] ' ' When multiple slices share the same underlying array, the changes made by each slice will be reflected in the array. "' Gopackage mainimport (" FMT ") Func Main (){numa: = [3]int{78, nums1]: = numa[:]//Creates a slice which contains all elements of the array nums2: = numa[:] Fmt. PRINTLN ("Array before change 1", NUMA) nums1[0] = the FMT. PRINTLN ("Array after modification to slice nums1", numa) nums2[1] = 101 FMT. PRINTLN ("Array after modification to slice nums2", numa)} ' [Online Run Program] (https://play.golang.org/p/mdNi4cs854) in line 9, ' Numa [:] ' missing start and end values. The default values for start and end are ' 0 ' and ' Len ' (NUMA), respectively. Two slices ' nums1 ' and ' nums2 ' share the same array. The output of the program is ' ' array before change 1 [[+] array after modification to slice nums1 [[+] array after modification to Slice NUMS2 [100 101 80] "It is clear from the output that each modification is reflected in the array when the slices share the same set of numbers. The length and capacity slices of the # # # Slice are the number of elements in the slice. * * The capacity of a slice is the number of elements in the underlying array starting from the creation of the tile index. * * Let's write a piece of code to better understand this. "' Gopackage 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 is 2 and CApacity is 6} "[Online Run Program] (https://play.golang.org/p/a1WOcdv827) in the above program, ' Fruitslice ' is created from the ' Fruitarray ' Index 1 and 2. Therefore, the length of ' Fruitlice ' is ' 2 '. The length of ' Fruitarray ' is 7. ' Fruiteslice ' was created from the index ' 1 ' of ' Fruitarray '. Therefore, the capacity of ' fruitslice ' is starting with ' Fruitarray ' Index of ' 1 ', that is, starting with ' orange ', the value is ' 6 '. Therefore, the capacity of ' Fruitslice ' is 6. The [program] (https://play.golang.org/p/a1WOcdv827) output slice has a length of 2 capacity of 6 * *. Slices can reset their capacity. Any exceeding this will cause the program to throw an error when it runs. "' Gopackage 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 fruitslic E = Fruitslice[:cap (Fruitslice)]//re-slicing furitslice till its capacity fmt. Println ("After re-slicing length was", Len (Fruitslice), "and capacity is", Cap (Fruitslice))} "[Running program online] (https:// PLAY.GOLANG.ORG/P/GCNZOOGICU) in line 11th of the above program, the capacity of ' Fruitslice ' is reset. The above program output is, "' length of slice 2 capacity 6 after re-Slicing length is 6 and capacity are 6 "# # # Use make to create a slice of Func make ([]t,len,cap) []t Create slices by passing type, length, and capacity. The capacity is an optional parameter, and the default value is the slice length. The Make function creates an array and returns a slice that references the array. "' Gopackage mainimport (" FMT ") func main () {i: = make ([]int, 5, 5) fmt. Println (i)} "[Online Run Program] (Https://play.golang.org/p/M4OqxzerxN) when creating tiles with make these values are zero by default. The output of the above program is ' [0 0 0 0 0] '. # # # Append the slice element as we already know the length of the array is fixed and its length cannot be increased. Slices are dynamic, and a new element can be appended to the slice using ' append '. The APPEND function is defined as ' func append (s[]t,x ... T) []t '. **x ... t** in a function definition indicates that the number of parameters x that the function accepts is variable. These types of functions are called [mutable functions] (https://golangbot.com/variadic-functions/). There is a problem that may be bothering you. If the slice is supported by an array, and the length of the array itself is fixed, how the slice has dynamic length. And what's going on inside, when a new element is added to the slice, a new array is created. The elements of the existing array are copied into the new array, and a new slice reference to the new array is returned. The new slice now has twice times the capacity of the old slice. It's cool,:). The following program will make you understand clearly. "Gopackage mainimport (" FMT ") func main () {cars: = []string{" Ferrari "," Honda "," Ford "} fmt. Println ("Cars:", cars, "have old length", Len (Cars), "and capacity", caps (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 are doubled to 6} "[Online Running program] (Https://play.golang.org/p/VUSXCOs1CF) in the above program, the capacity of ' cars ' was initially 3. In line 10th, we add a new element to cars and assign ' append ' (Cars, "Toyota") ' returned slices to cars. Now the capacity of cars doubled and became 6. The output of the above program is "' Cars: [Ferrari Honda Ford] have old length 3 and capacity 3 cars: [Ferrari Honda Ford Toyota] have new length 4 a nd capacity 6 "Slice type 0 value is ' nil '. The length and capacity of a ' nil ' slice is 0. You can use the Append function to append values to the ' nil ' slice. "' Gopackage 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)} "[Online Run Program] (Https://play.golang.org/p/x_-4XAJHbM) in the above program ' names ' is nil, we have added 3 A string to ' names '. The output of the program is "Slice is nil going to append names contents: [John Sebastian Vinay]" "You can also use the ' ... ' operator to add one slice to another slice. You can learn more about this operator in the variadic functions (https://golangbot.com/variadic-functions/) tutorial. "' Gopackage mainimport (" FMT ") func main () {veggies: = []string{" POTatoes "," tomatoes "," Brinjal "} Fruits: = []string{" oranges "," Apples "} Food: = Append (veggies, fruits ...) fmt. Println ("Food:", food)} ' [Online running program] (Https://play.golang.org/p/UnHOH_u6HS) on line 10th of the above procedure, food is through append (veggies, fruits ...) Create. The output of the program is ' food: [potatoes tomatoes brinjal oranges apples] '. The function passing of the # # # Slice We can assume that a slice can be represented internally by a struct type. This is its representation, "' gotype slice struct {length int capacity int zerothelement *byte} ' ' Slice contains the length, capacity, and pointer to the 0th element of the array. When a slice is passed to a function, even if it is passed by value, the pointer variable references the same underlying array. Therefore, when a slice is passed as a parameter to a function, changes made within the function are also visible outside the function. Let's write a program to check this. "' Gopackage 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 is visible outside} "[Running Program online] (https://play.golang.org/p/ IZQDIHNIFQ) in line number 17 of the above program, the calling function decrements each element in the slice by 2. These changes are visible when the slice is printed after the function call. If you remember that this is different from an array, the change to an array in the function is not visible outside the function. The above [program] (Https://play.golangThe output of. org/p/bwub6r-1bs) is, ' array before function call [8 7 6] array after function call [6 5 4] ' # # # A multidimensional slice is similar to an array, and a slice can have more than one dimension. "Gopackage mainimport (" FMT ") func main () {pls: = [][]string {" C "," C + + "}, {" JavaScript "}, {" Go "," Rust "},} for _, V 1: = range Pls {for _, V2: = Range V1 {fmt. Printf ("%s", v2)} FMT. Printf ("\ n")}} "[Online Run Program] (Https://play.golang.org/p/--p1AvNGwN) program output is, ' C C + + JavaScript Go Rust ' # # # A memory-optimized slice holds a reference to the underlying array. As long as the slices are in memory, the array cannot be garbage collected. In terms of memory management, this is a need to be aware. Let's say we have a very large array and we just want to deal with a small part of it. We then create a slice from this array and start processing the slices. It is important to note that the array still exists in memory when the slice is referenced. One workaround is to use the [copy] (https://golang.org/pkg/builtin/#copy) function ' func copy (dst,src[]t) int ' to generate a copy of the slice. So that we can use the new slices, the original array can be garbage collected. "' Gopackage 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)} "[Online Run Program] (Https://play.golang.org/p/35ayYBhcDE) in the above program on line 9th, ' neededcountries: = Countries[:len (countries)-2 ' Create a slice that removes the trailing 2 elements ' countries ', in 11 lines of the above program, copy ' Neededcountries ' to ' countriescpy ' Returns countriescpy at the same time on the next line of the function. Now the ' countries ' array can be garbage collected, because ' neededcountries ' is no longer referenced. I have compiled all the concepts we have discussed so far into one program. You can download it from [GitHub] (https://github.com/golangbot/arraysandslices). This is an array and a slice. Thank you for reading. Please leave your valuable comments and comments. * * Previous Tutorial-[switch statement] (https://studygolang.com/articles/11957) * * * Next tutorial-[variable Function] (https://studygolang.com/articles/12173) * *

via:https://golangbot.com/arrays-and-slices/

Author: Nick Coghlan Translator: Dingo1991 proofreading: Noluye polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

4,631 Reads
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.