-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08.arrays.go
58 lines (48 loc) · 1.47 KB
/
08.arrays.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// In Go, an array is a numbered sequence of elements of a
// specific length. In typical Go code, slices are much more
// common; arrays are useful in some special scenarios.
package main
import "fmt"
func main() {
// Here we create an array a that will hold exactly 5 ints. The
// type of elements and length are both of the array's
// type. By default an array is zero-valued, which for ints
// means 0s.
var a [5]int
fmt.Println("emp:", a)
// We can set a value at an index using the array[index] =
// value syntax, and get a value with array[index].
a[4] = 100
fmt.Println("set:", a)
fmt.Println("get:", a[4])
// The builtin len returns the length of an array.
fmt.Println("len:", len(a))
// Use this sintax to declare and initialize an array in one
// line.
b := [5]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
// You can also have the compiler count the number of
// elements for you with ...
b = [...]int{1, 2, 3, 4, 5}
fmt.Println("dcl:", b)
// If you specify the index with :, the elements in between
// will be zeroed.
b = [...]int{100, 3: 400, 500}
fmt.Println("idx:", b)
// Arrays types are one-dimensional, but you can compose
// types to build multi-dimensional data structures.
var twoD [2][3]int
for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ {
twoD[i][j] = i + j
}
}
fmt.Println("2d:", twoD)
// You can create and initialize multi-dimensional arrays at
// once to.
twoD = [2][3]int{
{1, 2, 3},
{1, 2, 3},
}
fmt.Println("2d:", twoD)
}