0
0
Goprogramming~10 mins

Slice length and capacity in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a slice with length 3.

Go
s := make([]int, [1])
fmt.Println(len(s))
Drag options to blanks, or click blank then click option'
A5
B0
C3
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Using capacity instead of length in the make function.
Confusing length with capacity.
2fill in blank
medium

Complete the code to create a slice with length 3 and capacity 5.

Go
s := make([]int, 3, [1])
fmt.Println(cap(s))
Drag options to blanks, or click blank then click option'
A0
B10
C3
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Setting capacity smaller than length causes a compile error.
Confusing length and capacity positions in make.
3fill in blank
hard

Fix the error in the code to print the length of the slice.

Go
s := []int{1, 2, 3}
fmt.Println([1](s))
Drag options to blanks, or click blank then click option'
Acap
Blen
Csize
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using cap instead of len to get length.
Using non-existent functions like size or length.
4fill in blank
hard

Fill both blanks to create a slice with length 2 and capacity 4, then print length and capacity.

Go
s := make([]int, [1], [2])
fmt.Println(len(s), cap(s))
Drag options to blanks, or click blank then click option'
A2
B3
C4
D5
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping length and capacity values.
Setting capacity smaller than length.
5fill in blank
hard

Fill the blanks to create a slice from an array, then print its length and capacity.

Go
arr := [5]int{1, 2, 3, 4, 5}
s := arr[[1]:[2]]
fmt.Println(len(s), cap(s))
Drag options to blanks, or click blank then click option'
A1
B2
C5
D3
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing slice length with capacity.
Using wrong indices for slicing.