0
0
Goprogramming~10 mins

Passing values vs pointers in Go - Interactive Practice

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

Complete the code to declare a function that takes an integer value.

Go
func increment([1] int) int {
    return [1] + 1
}
Drag options to blanks, or click blank then click option'
Anum
B*num
C&num
Dval
Attempts:
3 left
💡 Hint
Common Mistakes
Using * or & in the parameter name when passing by value.
2fill in blank
medium

Complete the code to declare a function that takes a pointer to an integer.

Go
func incrementPointer([1] *int) {
    *[1] = *[1] + 1
}
Drag options to blanks, or click blank then click option'
Aptr
Bval
Cnum
Dx
Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent variable names inside the function.
3fill in blank
hard

Fix the error in the code to correctly modify the original variable using a pointer.

Go
func main() {
    x := 5
    incrementPointer([1]x)
    fmt.Println(x)
}
Drag options to blanks, or click blank then click option'
Ax
B&
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the variable without & when a pointer is expected.
4fill in blank
hard

Fill both blanks to create a function that swaps two integers using pointers.

Go
func swap([1] *int, [2] *int) {
    temp := *a
    *a = *b
    *b = temp
}
Drag options to blanks, or click blank then click option'
Aa
Bb
Cx
Dy
Attempts:
3 left
💡 Hint
Common Mistakes
Using parameter names that don't match the function body.
5fill in blank
hard

Fill all three blanks to call the swap function correctly in main.

Go
func main() {
    x, y := 3, 4
    swap([1][2], [3]y)
    fmt.Println(x, y)
}
Drag options to blanks, or click blank then click option'
A&
Bx
C,
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Passing values instead of pointers to swap.
Missing the comma between arguments.