Arrays

An array is a fixed length sequence of zero or more elements of a particular type.

By default the elements of a new array are set to zero.

example.go Run code

package main

import (
	"fmt"
)

func main() {
	// Declare an integer array of five elements.
	var nums [5]int 
	fmt.Println(nums)  
}

E:\golang\excercise>go run example.go
[0 0 0 0 0]

Set and get array elements

example.go Run code

package main

import (
	"fmt"
)

func main() {
	// Declare an integer array of 3 elements.
	var nums [3]int

	// Set values
	nums[0] = 10
	nums[1] = 20
	nums[2] = 30

	// Get values
	fmt.Println(nums[0])
	fmt.Println(nums[1])

	// Print length of array
	fmt.Println("length =", len(nums))

	// Print indices and elements
	for i, v := range nums {
		fmt.Printf("%d %d\n", i, v)
	}
}

E:\golang\excercise>go run example.go
10
20
length = 3
0 10
1 20
2 30

declare and initialize an array in one line

example.go Run code

Array literals allow to declare the number of elements and specify values for those elements.

package main

import (
	"fmt"
)

func main() {
        // Declare an integer array of five elements.
        // Initialize each element with a specific value.
	nums := [5]int{10, 20, 30, 40, 50}
	fmt.Println(nums)
}

E:\golang\excercise>go run example.go
[10 20 30 40 50]

In an array literal, if an ellipsis “…” appears in place of the length, the array length is determined by the number of initializers.

example.go Run code

package main

import (
	"fmt"
)

func main() {
	nums := [...]int{1, 2, 3, 4, 5}
	fmt.Println(nums)
	fmt.Printf("%T\n", nums)
}

E:\golang\excercise>go run example.go
[1 2 3 4 5]
[5]int

Leave a Reply

Your email address will not be published. Required fields are marked *