The third parameter of Golang make ()
Study for a period of time Golang, probably can use Golang to do some small things, so review some of the basic things. Golang allocated memory has a make function, the first parameter of the function is the type, the second argument is the allocated space, the third parameter is the reserved allocation space, the first two parameters are well understood, but I have a face to the third parameter, such as A:=make ([]int, 5, ten), Len (a) The output is 5,cap (a) output is 10, and then I to a[4] assignment found is can get, but to a[5] to assign value found error, so depressed this reserve allocated space how to use it, so Google a bit to find that the original reserved space needs to be re-sliced to use, So make a record, the code is as follows.
Packagemain
Import "FMT"
Funcmain () {
A: =make ([]int,10,20)
Fmt. Printf ("%d,%d\n", Len (a), Cap (a))
Fmt. Println (a)
B: = A[:cap (a)]
Fmt. Println (b)
}
Output results
10,20
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
Problem resolution for value passing in for loop
Problem Description:
Iterate through an array and modify the values in them:
Package Main
Import (
"FMT"
)
Type Link struct {
a int
}
Func Main () {
Arr: = Make ([]link, 10)
For I, V: = Range arr {
V.A = i
}
For _, V: = Range arr {
Fmt. Println (V.A)
}
}
Expected output, all V.A in the array are modified to the values in I
Actual output, none of the V.A in the array has changed
Problem analysis
In the Go For...range loop, go always uses the value copy instead of the traversed element itself, simply, that value in For...range is a duplicate value copy , not the element itself. A property cannot be modified by & (address).
Solution: Directly call an array
Package Main
Import (
"FMT"
)
Type Link struct {
a int
}
Func Main () {
Arr: = Make ([]link, 10)
For I, _: = Range Arr {
ARR[I].A = i
}
For _, V: = Range arr {
Fmt. Println (V.A)
}
}