0
0
Goprogramming~10 mins

Why pointers are needed in Go - Test Your Understanding

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

Complete the code to declare a pointer to an integer variable.

Go
var x int = 10
var p [1] = &x
Drag options to blanks, or click blank then click option'
A*int
Bint
C&int
Dpointer
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' instead of '*int' for pointer type.
Using '&int' which is invalid syntax.
2fill in blank
medium

Complete the code to change the value of x using its pointer p.

Go
var x int = 5
var p *int = &x
*p [1] 20
fmt.Println(x)
Drag options to blanks, or click blank then click option'
A==
B&
C:=
D=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '==' which is a comparison, not assignment.
Using ':=' which declares a new variable.
3fill in blank
hard

Fix the error in the code to correctly swap two integers using pointers.

Go
func swap(a, b [1] int) {
    temp := *a
    *a = *b
    *b = temp
}

x, y := 1, 2
swap(&x, &y)
fmt.Println(x, y)
Drag options to blanks, or click blank then click option'
Apointer
B*
Cref
D&
Attempts:
3 left
💡 Hint
Common Mistakes
Using '&' which is the address operator, not a type.
Using 'ref' or 'pointer' which are not Go types.
4fill in blank
hard

Fill both blanks to correctly swap values of two integers using pointers.

Go
func swap(a, b [1] int) {
    temp := *a
    *a = *b
    *b = temp
}

x, y := 3, 4
swap([2]x, &y)
fmt.Println(x, y)
Drag options to blanks, or click blank then click option'
A*
B&
Cref
Dpointer
Attempts:
3 left
💡 Hint
Common Mistakes
Passing variables directly instead of their addresses.
Using 'ref' or 'pointer' which are not valid Go types.
5fill in blank
hard

Fill all three blanks to create a function that increments an integer value using a pointer.

Go
func increment([1] [2]int) {
    *[3] += 1
}

var num int = 7
increment(&num)
fmt.Println(num)
Drag options to blanks, or click blank then click option'
Ap
B*
C&
Dptr
Attempts:
3 left
💡 Hint
Common Mistakes
Using '&' as a type instead of '*'.
Using different names for parameter and dereference.