Go language basics 2
len&cap
Continuing with the above, we mentioned that the array of the second dimension in a two-dimensional array cannot be used...
Let's express that we will know two new functions, respectivelylenandcap
package main func main() { a := [2]int{} println(len(a), cap(a)) }
From the above code, we aremainA function defines aarray,Length is 2,No assignment operations such as initialization variables are performed,soAll array elements are 0; The output of the array a is calledlength
andcap
Value, hereAll run results are 2
Traversal of two-dimensional arrays
Next, let's focus onTraversal of two-dimensional arraysSome friends may ask: I haven’t learned any traversal loops, how do I understand this?
Don't worry, we mainly look at a thought process when looking at the code~
package main import ( "fmt" ) func main() { var f [2][3]int = [...][3]int{{1, 2, 3}, {7, 8, 9}} for k1, v1 := range f { for k2, v2 := range v1 { ("(%d,%d)=%d ", k1, k2, v2) } () } }
First we can seemain
A function defines aint
type,Named fThe array of properties are2 rows and 3 columns, the first line stores{1,2,3}, the second line stores{7,8,9}, we passfor loopA two-dimensional array is traversed once, and readers can temporarily understand it as a fixed format of a loop. The subsequent loop will introduce it to readers one by one.Since this array is a two-dimensional array, so we need to callTwo for loopsTo traverse the array, print out the required value through the function
Copying and passing parameters of arrays
package main import "fmt" func printArr(arr *[5]int) { arr[0] = 10 for i, v := range arr { (i, v) } } func main() { var arr1 [5]int printArr(&arr1) (arr1) arr2 := [...]int{2, 4, 6, 8, 10} printArr(&arr2) (arr2) }
First we can see that aprintArrMethod, and a built-in methodLength is 5, int typearray. Then weAssign the first element of the array to 10, then loop through the array,Output the index of the array and the value at the index position respectively
Go back to the main method, we define aArray named arr1, length 5, type int, and directly print the address value of the array. At the same time, call the function to print out the value of the array when the array was not initialized. It is obvious that since we have modified the value of the array with index position 1 in printArr, when we print out the array this time, we will also be affected by the previous array, so the result of the printing output of this array is[10 0 0 0 0]
. Then we defined aNamed arr2, with an arbitrary length, int type array, and the assignment operation is given at the same time, but becauseprintArrmiddleThe value of the position of the array with index 1 has changed, so this timearr2 arrayThe result of the printout is[10 4 6 8 10]
Find the sum of all elements in the array
package main import ( "fmt" "math/rand" "time" ) func sumArr(a [10]int) int { var sum int = 0 for i := 0; i < len(a); i++ { sum += a[i] } return sum } func main() { (().Unix()) var b [10]int for i := 0; i < len(b); i++ { b[i] = (1000) } sum := sumArr(b) ("sum=%d\n", sum) }
We first define a method calledsumArr, and pass it into the method at the same timeAn array named a, length 10, and data type int. In this method, we define a variable assum,usefor loopTo traverse the array,Use sum to record the sum of each element of the array, finally return the value of sum
Then we see the main method, in which we use()
Function to define a random number and initialize aAn array named b, length 10, data type intUse a for loop to traverse the array, and at the same timeAssign the value of a random number to the element in the b array. UltimatelyAssign the value of b in the array sumArr to sum, call the function to performPrint out the value of sum
Example: Array element matching problem
Find the subscript of two elements in the array with sum as a given value, such as array [1,3,5,8,7],
Find out the subscripts whose sum of two elements equals 8 are (0, 4) and (1, 2)
Find the sum of elements, which is the given value
package main import "fmt" func myTest(a [5]int, target int) { // traverse array for i := 0; i < len(a); i++ { other := target - a[i] // Continue to traverse for j := i + 1; j < len(a); j++ { if a[j] == other { ("(%d,%d)\n", i, j) } } } } func main() { b := [5]int{1, 3, 5, 8, 7} myTest(b, 8) }
According to the question, we can know thatmyTest
We define aAn array named a, length 5, and data type int, and also defines a target valuetarget
Used to check the elements and whether they are correct.
Then we traverse the array and defineother
Variables are used to represent another array element, the reason for quadratic traversal here isBecause this question needs to match the values of two elements in the array, so a quadratic traversal matches the value of i in the array, once withother
On the match, that isPrint out the value of this array (two elements) 。
We're inmain
The function in theArray b performs assignment operation for variable initializationso that the method can be called, if it can be found in the arraymyTest()
The second method, i.e.target
Elements, print out these two elements, otherwise print nothing
Today's summary
Today we mainly learnGo languageexistSome applications in two-dimensional arrays and traversal arrays. likeA fixed format for traversing an array, orCopying and passing parameters of arrays, these are all worthy of careful consideration by readers
This is the end of this article about a brief analysis of these details of arrays in Go. For more related Go language array content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!