In the Golang language, an array name is passed as an argument to a function, and the action behind it is to produce a copy of the array, and the operation of the array copy in the function does not affect the original array itself. Like the following example
Package Mainimport "FMT" Func Main () {arr: = [5]int{1, 2, 3, 4, 5}fmt. Println (arr)//1 2 3 4 5Do (arr)//try to clear arr 0 fmt. Println (arr)//1 2 3 4 5}func do (arr [5]int) {For I, _: = Range arr {arr[i] = 0}}
As you can see, the value of the original array has not changed after trying to change the elements of the arrays.
To achieve the goal, it is natural to think of the array pointer, in the main function, the first address of the array as a parameter to the function, the function receives a pointer, and then with a For loop array operation, and finally, it is achieved the purpose of modifying the array element.
Package Mainimport "FMT" Func Main () {arr: = [5]int{1, 2, 3, 4, 5}fmt. Println (arr)//1 2 3 4 5Do (&arr)//try to clear arr 0 fmt. Println (arr)//0 0 0 0 0}func do (arr *[5]int) {For I, _: = Range arr {arr[i] = 0}}
However, this code looks particularly awkward, why, because the function do array length is specified beforehand (5 in the above example), and want the function to run normally, the implementation of the specified length is the same as the length of the argument array, otherwise there will be "type error", this is very troublesome, because this is the syntax of the Go language rules , it must be adhered to.
A private attempt:
1== "When defining a function, omit the array length of the formal parameter or use" ... "
2== "in the main function, when defining an array, the length of the array is omitted or used" ... "
3== "Two places are omitted or use" ... "
Without exception, the previous attempt failed, and by this time the method of using the array pointer was not working, but it could be done using slice.
A For loop uses range to iterate over an array to try to modify the value of an element