Arrays
Define Arrays
We use var array_name [num] data_type to define arrays in Go.
1 | package main |
The outputs will be
1 | [0 0 0 0 0] [1 3 5] [4 5 6 7 8 9] |
Define 2-D Arrays
We could define a 2-D array:
1 | package main |
The output will be
1 | [[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]] |
Iterate through arrays
for loop
Use for loop to iterate through array itemes.
1 | func main() { |
The outputs will be:
1 | 12 |
Here is a very important concepts:
Functions are compressed arrays; arrays are expanded functions
for...range...
The for loop can be simplified with for...range
1 | func main(){ |
The outputs will be:
1 | 4 |
With for...range we could get the index, as well as the value
1 | func main() { |
The outputs will be:
1 | Index is: 0 --- Value is: 4 |
Here if we just need value not index, we could use _ to ommit index
1 | for _, v := range arr{ |
Syntax Candy range
Why do we need range? It’s both self-explanatory and elegant. Let’s compare with other languages:
- In C/C++, there no such similar built-in features, some 3rd party libs will support this behavior
- In Python, we have both built-in
rangeand some powerful functions such asarangefromnumpy. Also in Python we could useenumerate
1 | lang = ["go", "python", "c++", "javascript", "java"] |
The outputs will be:
1 | Index is 0 --- Value is go |
Go Arrays are value type
Let’s define a function called printArray
1 | package main |
In printArray the parameter is arr [5]int, so the function can only take arrays of 5 items, aka [5]int is different from [10]int
Note the parameter can alternatively be arr []int, but this is a slice of array, only arr[5]int is the “true” array.
Value Type
Because arrays are value type, so when we invoke the function printArray, a copy of arr2 will be passed. We pass by the value.
If we try to change some element in the function block, it will not affect the array arr2.
Whereas in other languages such as C, the address of the first element of the array will be passed, as a result, the array elements in C could get affected.
1 | package main |
The output will still be:
1 | Index is: 0 --- Value is: 100 |
Because invoking printArray will not change the elements in arr2.
Pointing to Array
We could change the array elements by refactor the function and pass in an Array Pointer as the function argument.
1 | func printArrayPointer(arr *[5]int) { |
Unlike in C, when we invoke printArrayPointer, we need to convert the argument to an array pointer, whereas in C the array name is the address pointing to the first element of the array
The output will become:
1 | Calling printArray |
To summarize
[5]intand[10]intare two different data types- Invoking
func f(arr [10]int)will “copy” the array. - We could pass array pointers as function arguments to “mutate” array elements