This is a creation in Article, where the information may have evolved or changed.
Let's look at a simple array definition:
var array [3]int
The above statement defines a variable array
, which is an array type that contains an 3
integer. You can use Go
the language built-in len
functions to get the array length:
package mainimport ( "fmt")func main() { var array [3]int fmt.Println(len(array))}
Execute the above procedure result:
3
It is important to note that in a Go
language, the length of an array is part of an array type, and it must be a constant expression, that is, the value of the length is available at program compile time. Take a look at the following procedure:
package mainimport ( "fmt")func print_array(array []int) { fmt.Printf("In function, array is %v\n"array)}func main() { array [3]int print_array(array )}
Compiling this program will result in the following error:
use array (type [3]int) as type []int in argument to print_array
Go
The language requires that the type of the parameters and arguments passed into the function must be exactly the same, and array
the type is [3]int
, not []int
, so the compilation will go wrong.
Go
Language function parameters are call-to-value, so if the function's arguments are arrays, then the actual incoming copy will be the original array. Take a look at this example:
Package mainimport ("FMT")func change_array(array [3]int ) { forI, _: = RangeArray{Array[I] =1} FMT. Printf ("in function, array address was%p, value is%v\n", &Array,Array)}func main() {varArray[3]intFmt. Printf ("Original array address is%p, value is%v\n", &Array,Array) Change_array (Array) FMT. Printf ("Changed array address is%p, value is%v\n", &Array,Array)}
Execution Result:
Original array address is 0xc082006560 , value is [0 0 0 ]in function, array Address is 0xc0820065e0 , value is [1 1 1 ] Changed Array address is 0xc082006560 , value is [0 0 0 ]
As you can see, the array address that is manipulated in the function is change_array
not the array address in the function, and the value of the array in the main
function has main
change_array
not changed before or after the function is called.
if the element type of an array is comparable, then the array type is comparable, that is, you can use the and operator to operate on an array of ==
!=
pairs. take a look at the following example:
package mainimport "fmt"func main() { a := [...]int{2, 1} b := [...]int{1, 2} fmt.Println(a == b, a != b)}
The results of the implementation are as follows:
false true