table of Contents
table of Contents
@
Precautions
- An array of value types in Go are not quoted
- You may be used between the same type and length or an array ==! = Compare (Go has been achieved), but no <or>
Go supports multi-dimensional arrays
Array definition
Tips
- The two arrays can not be directly assigned
- Array definition format:
var <Varname> [n]<type>, n>=0
- Type is part of the array length, the array of different lengths and therefore different types of
The index value can be initialized at a position denoted n
Examples
func main(){
var a [20]int
a = [20]int{19:1} //索引
b := [3]string{}
c := [...]int{0:1, 1:2, 2:3}
fmt.Println(a,b,c)
}
Pointer to an array of arrays and pointers
Examples
func main(){
var a [20]int
a = [20]int{19:1}
var p *[20]int = &a
fmt.Println(*p)
}
func main(){
x,y := 1,2
var pp [20]*int = [20]*int{&x, &y}
fmt.Println(pp)
}
Tips
- Create an array with the new, this method returns a pointer to an array
- Whether array itself or a pointer to an array, the array values can be changed by way of brackets
func main(){
a := [10]int{}
a[1]=3
fmt.Println(a)
p := new([10]int)
p[1]=3
fmt.Println(p)
}
/*
command-line-arguments
[0 3 0 0 0 0 0 0 0 0]
&[0 3 0 0 0 0 0 0 0 0]
*/
Multidimensional Arrays
- You can also use a multidimensional array index
- The first parameter is a two-dimensional array [...] can be omitted, but the second can not
func main(){
a := [2][3]int{
{1,2,3},
{4,5,6}}
fmt.Println(a)
}
/*
> Output:
[[1 2 3] [4 5 6]]
*/
The following code will complain:
func main(){
a := [2][3]int{
{1,2,3},
{4,5,6}
}
fmt.Println(a)
}
//注意数组右大括号的位置
Bubble sort example
func main(){
a := [...]int{1,3,4,6,8,2,10,45,34,9,8}
fmt.Println(a)
fmt.Println("从小到大排序")
num := len(a)
for i := 0; i < num; i++ {
for j := i+1; j<num; j++{
if a[i]>a[j] {
temp := a[i]
a[i] = a[j]
a[j] = temp
}
}
}
fmt.Println(a)
}
/*
> Output:
command-line-arguments
[1 3 4 6 8 2 10 45 34 9 8]
从小到大排序
[1 2 3 4 6 8 8 9 10 34 45]
*/