-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrays
83 lines (51 loc) · 1.97 KB
/
Arrays
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
## Declaring and Initializing Arrays
In Go, you can declare an array using the `var` keyword followed by the array name, size, and element type. For example:
```go
var arr [5]int
```
This declares an array named `arr` with a size of 5 and elements of type `int`.
You can also initialize an array with values during declaration:
```go
arr := [5]int{1, 2, 3, 4, 5}
```
Or let the compiler infer the size:
```go
arr := [...]int{1, 2, 3, 4, 5}
```
## Accessing Array Elements
You can access array elements using the index operator `[]`. Array indices start at 0, so the first element is accessed with `arr`. For example:
```go
fmt.Println(arr[0]) // Output: 1
```
## Modifying Array Elements
You can modify array elements by assigning a new value to the specific index:
```go
arr[0] = 10
```
This sets the first element of `arr` to 10.
## Array Operations
Go provides several built-in functions to work with arrays:
- `len(arr)`: Returns the length of the array
- `cap(arr)`: Returns the capacity of the array (same as length for arrays)
You can also use slicing to create subarrays:
```go
subArr := arr[1:3]
```
This creates a new slice `subArr` that references a portion of `arr`, containing elements at indices 1 and 2.
## Multi-Dimensional Arrays
Go supports multi-dimensional arrays. For example, a 2D array can be declared as:
```go
var matrix [3][3]int
```
This creates a 3x3 2D array of integers.
You can initialize a 2D array during declaration:
```go
matrix := [3][3]int{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
```
Access elements using double indexing:
```go
fmt.Println(matrix[1][1]) // Output: 5
```
## Limitations of Arrays
Arrays in Go have a fixed size that is determined when they are declared. This means that once an array is created, its size cannot be changed. If you need a data structure with a dynamic size, consider using slices instead.
Slices provide more flexibility and are built on top of arrays, allowing you to resize and manipulate the underlying array efficiently.