Array types in Golang

Arrays are a collection of elements of the same type. They are used to store a fixed-size sequence of elements, and each element can be accessed using its index. In Golang, arrays are declared using the following syntax:

var arr [size]datatype

Here, size is the number of elements in the array, and datatype is the type of the elements. For example, to declare an array of 5 integers, you can write:

var numbers [5]int

You can also initialize the values of an array during declaration, like this:

var days = [7]string{“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”}

In this example, an array of 7 strings is declared and initialized with the names of the days of the week.

To access the elements of an array, you can use their index. The index of the first element is 0, and the index of the last element is size-1. For example, to print the second element of the numbers array declared earlier, you can write:

fmt.Println(numbers[1])

Practice Questions on array types in Golang

Here are some practice questions on array types in Golang:

What is the syntax for declaring an array of 10 integers in Golang?

A. var arr [10]int
B. var arr = [10]int{}
C. var arr []int = make([]int, 10)
D. var arr [int]10

Answer: A

What is the index of the last element in an array of size 8?

A. 7
B. 8
C. 9
D. 10

Answer: A

What is the output of the following Go code?

package main

import “fmt”

func main() {
var nums = [3]int{1, 2, 3}

for i := 0; i < len(nums); i++ {
fmt.Println(nums[i])
}
}

A. 1 2 3
B. 1
C. 2
D. 3

Answer: A

What is the syntax for initializing the first element of an array to 10?

A. var arr [1]int = {10}
B. var arr = [1]int{10}
C. var arr []int = make([]int, 1); arr[0] = 10
D. var arr [10]int; arr[0] = 10

Answer: B

What is the output of the following Go code?

package main

import “fmt”

func main() {
var arr = [5]string{“a”, “b”, “c”, “d”, “e”}

fmt.Println(arr[2])
fmt.Println(len(arr))
}

A. c 5
B. b 4
C. c 4
D. d 5

Answer: A

Arithmetic operators in Golang
Assert in Golang

Get industry recognized certification – Contact us

keyboard_arrow_up