2.4 KiB
2.4 KiB
Slices vs Arrays Quiz
Why you want to use a slice instead of an array?
- I like arrays more
- I want to create a dynamic collection, so I need an array
- A slice's length is dynamic, so I can create dynamic collections CORRECT
Where does the length of a slice belong to?
- Compile-Time
- Runtime CORRECT
- Walk-Time
- Sleep-Time
2: A slice's length is not a part of its type. So its length can change at runtime.
Which function call below is correct?
// Let's say there's a function like this.
func sort(nums []int) {
// ...
}
- sort([...]int{3, 1, 6})
- sort([]int32{3, 1, 6})
- sort([]int{3, 1, 6}) CORRECT
1: You can't call the sort function using an array. It expects an int slice.
2: You can't call the sort function using an int32 slice. It expects an int slice.
3: That's right! You can pass an int slice to the sort function.
What is the zero value of this slice?
var tasks []string
- 0
- 1
- nil CORRECT
- unknown
3: This is a nil slice. Unlike an array, a slice's zero value is nil.
What does this code print?
var tasks []string
fmt.Println(len(tasks))
- 0 CORRECT
- 1
- nil
- It doesn't work.
1: Yes, you can use the len function on a nil slice. It returns 0 because the slice doesn't contain any elements yet.
What does this code print?
var tasks []string
fmt.Println(tasks[0])
- 0
- 1
- nil
- It doesn't work. CORRECT
4: You can't get an element that does not exist. A nil slice does not contain any elements.
Which declaration below is a correct slice declaration?
- [...]int{}
- [2]string{"hello", "world"}
- []string{"hello", "world"} CORRECT
- string[2]{"hello", world"}
This code doesn't work, why?
colors := []string{"red", "blue", "green"}
tones := []string{"dark", "light"}
if colors == tones {
// ...
}
- The slices have different lengths
- If statement doesn't contain any statements
- Slices cannot be compared CORRECT
3: That's right! A slice value can only be compared to a nil value.
What is the length of this slice?
[]uint64{}
- 64
- 1
- 0 CORRECT
- Error
3: That's right. This is an empty slice, it doesn't contain any elements.
What is the length of this slice?
[]string{"I'm", "going", "to", "stay", "\"here\""}
- 0
- 1
- 2
- 3
- 4
- 5 CORRECT