How to initialize an Array with an Array Literal in Go?
You can initialize an array with pre-defined values using an array literal. An array literal have the number of elements it will hold in square brackets, followed by the type of its elements. This is followed by a list of initial values separated by commas of each element inside the curly braces.
Example
package main
import "fmt"
func main() {
x := [5]int{10, 20, 30, 40, 50} // Intialized with values
var y [5]int = [5]int{10, 20, 30} // Partial assignment
fmt.Println(x)
fmt.Println(y)
}
Output
[10 20 30 40 50]
[10 20 30 0 0]
Most Helpful This Week
Initialize values for specific array elements in Go
How to iterate over an Array using for loop?
Golang check if array element exists
What is an Array in Go?
Initializing an Array with ellipses in Go
How to assign and access array element values in Go?
Copy an array by value and reference into another array
Declaring an Integer or String Array of Five Elements in Go
Tricks to filter array elements in Go