0
0
Goprogramming~5 mins

Array initialization in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an array in Go?
An array in Go is a fixed-size collection of elements of the same type stored in contiguous memory locations.
Click to reveal answer
beginner
How do you declare and initialize an array of 3 integers with values 1, 2, and 3 in Go?
You can declare and initialize it like this:
var arr = [3]int{1, 2, 3}
Click to reveal answer
beginner
What happens if you declare an array without initializing it in Go?
The array elements are automatically set to the zero value of the element type. For integers, this is 0.
Click to reveal answer
intermediate
How can you let Go infer the size of an array when initializing it?
Use [...] instead of a fixed size. Example:
arr := [...]int{4, 5, 6}
lets Go count the elements and set the size to 3.
Click to reveal answer
intermediate
Can you initialize an array with some elements and leave others to zero values in Go?
Yes. You can specify values for some indices and the rest will be zero. Example:
arr := [5]int{0: 10, 3: 20}
sets index 0 to 10, index 3 to 20, others to 0.
Click to reveal answer
How do you declare an array of 4 strings in Go with all elements initialized to empty strings?
Avar arr []string = {"", "", "", ""}
Bvar arr [4]string
Carr := [4]string{"", "", "", ""}
Darr := []string{4}
What does this code do? arr := [...]int{1, 2, 3, 4}
ADeclares an array of 4 integers with values 1, 2, 3, 4
BDeclares an array of size 3 with values 1, 2, 3
CDeclares a slice of 4 integers
DDeclares a pointer to an array
What is the zero value of an int array element in Go?
Aempty string
Bnil
Cundefined
D0
How do you initialize only the first and last elements of a 5-element int array in Go?
Aarr := [5]int{1, 0, 0, 0, 5}
Barr := [5]int{0: 1, 4: 5}
CBoth A and B
DNeither A nor B
Which of these is NOT a valid way to declare an array in Go?
Avar arr []int = [3]int{1, 2, 3}
Barr := [...]int{1, 2, 3}
Carr := [3]int{1, 2, 3}
Dvar arr [3]int
Explain how to declare and initialize an array in Go with specific values.
Think about using [size]type{values} or [...]type{values}.
You got /3 concepts.
    Describe what happens when you declare an array without giving initial values in Go.
    Consider what Go sets each element to automatically.
    You got /3 concepts.