0
0
Goprogramming~10 mins

Pointer behavior in functions 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 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'
Aint
B*int
C&int
Dint*
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' instead of '*int' for pointer type.
Using '&int' which is not a valid type.
Using 'int*' which is not Go syntax.
2fill in blank
medium

Complete the code to modify the value of an integer through a pointer inside a function.

Go
func changeValue(n [1]) {
    *n = 20
}

func main() {
    x := 10
    changeValue(&x)
    fmt.Println(x) // Output: 20
}
Drag options to blanks, or click blank then click option'
A*int
Bint
Cint*
D&int
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' instead of '*int' so the function modifies a copy.
Using invalid pointer syntax like 'int*' or '&int'.
3fill in blank
hard

Fill both blanks to make the increment function modify x correctly.

Go
func increment(n [1]) {
    (*n)++
}

func main() {
    x := 5
    increment([2]x)
    fmt.Println(x) // Output: 6
}
Drag options to blanks, or click blank then click option'
Aint
B&
C*int
Dpointer
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' instead of '*int' in the function parameter.
Passing 'x' instead of '&x' to the function.
4fill in blank
hard

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

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

func main() {
    x, y := 1, 2
    swap([2]x, &y)
    fmt.Println(x, y) // Output: 2 1
}
Drag options to blanks, or click blank then click option'
A*int
B&
Cint
Dpointer
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' instead of '*int' for parameters.
Passing variables directly instead of their addresses.
5fill in blank
hard

Fill all three blanks to create a function that doubles the value of an integer using a pointer and returns the new value.

Go
func doubleValue(n [1]) [2] {
    *n = *n * 2
    return [3]
}

func main() {
    x := 7
    result := doubleValue(&x)
    fmt.Println(result, x) // Output: 14 14
}
Drag options to blanks, or click blank then click option'
A*int
Bint
C*n
Dn
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'int' instead of '*int' for the parameter.
Returning the pointer variable instead of the dereferenced value.
Using wrong return type.