This is the 4th day of my participation in the August More Text Challenge
An array in Go is a data structure of a specific type and fixed length. They can have zero or more elements, and you must define the size when you declare or initialize them. Furthermore, once they are created, they cannot be resized. For these reasons, arrays are not often used in Go programs, but they are the basis for slicing and mapping.
Declare an array
To declare an array in Go, you must define the data types of its elements and the number of elements that the array can hold. Each element in the array can then be accessed using subscript notation, where the first element is 0 and the last element is the array length minus 1 (length -1).
For example, let’s use the following code:
package main
import "fmt"
func main(a) {
var a [3]int
a[1] = 10
fmt.Println(a[0])
fmt.Println(a[1])
fmt.Println(a[len(a)- 1])}Copy the code
The output is as follows:
10 0 0Copy the code
Even if an array is declared, no errors are encountered when accessing its elements. By default, Go initializes each element with the default data type. In this case, int defaults to zero. However, you can assign values to specific locations. That’s why you see a[1] = 10. You can access the element using the above notation. Also notice that to print out the first element, we use a[0]. To print out the last element, we use a[len(a)-1]. The len function is a built-in function in Go to get the number of elements in an array, slice, or map.
Initializing an array
When declaring an array, you can also initialize the array with non-default values. For example, you can use the following code to view and test the syntax:
package main
import "fmt"
func main(a) {
cities := [5]string{"New York"."Paris"."Berlin"."Madrid"}
fmt.Println("Cities:", cities)
}
Copy the code
The output is as follows:
Cities: [New York Paris Berlin Madrid ]
Copy the code
Even though the array should have five elements, there is no need to assign values to all elements. As shown above, the latest location contains an empty string because it is the default value for the string data type.
An ellipsis in an array
If you don’t know how many positions you will need, but know how much data you will have, another way to declare and initialize an array is to use ellipsis (…). , as shown in the following example:
q := [...]int{1.2.3}
Copy the code
Modify the code as follows:
package main
import "fmt"
func main(a) {
cities := [...]string{"New York"."Paris"."Berlin"."Madrid"}
fmt.Println("Cities:", cities)
}
Copy the code
The output is as follows:
Cities: [New York Paris Berlin Madrid]
Copy the code