0
0
Goprogramming~20 mins

Pointer behavior in functions in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Pointer Mastery in Go
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Go code with pointer parameter?

Consider this Go program that modifies a variable through a pointer parameter. What will it print?

Go
package main
import "fmt"

func modify(x *int) {
    *x = *x + 10
}

func main() {
    a := 5
    modify(&a)
    fmt.Println(a)
}
A5
B10
C15
DCompilation error
Attempts:
2 left
💡 Hint

Think about what happens when you change the value at the memory address the pointer points to.

Predict Output
intermediate
2:00remaining
What does this Go code print when passing a pointer to a struct?

Look at this Go code that changes a struct field via a pointer. What is printed?

Go
package main
import "fmt"

type Point struct {
    x int
    y int
}

func move(p *Point) {
    p.x = 10
    p.y = 20
}

func main() {
    pt := Point{1, 2}
    move(&pt)
    fmt.Println(pt.x, pt.y)
}
A1 2
B10 20
C0 0
DCompilation error
Attempts:
2 left
💡 Hint

Remember that pointers to structs allow modifying the original struct fields.

🔧 Debug
advanced
2:00remaining
Why does this Go function not change the original variable?

Examine this Go code. The function tries to change the value of num but it does not work. Why?

Go
package main
import "fmt"

func changeValue(x int) {
    x = 100
}

func main() {
    num := 50
    changeValue(num)
    fmt.Println(num)
}
ABecause <code>changeValue</code> receives a copy of <code>num</code>, not a pointer
BBecause <code>num</code> is a constant and cannot be changed
CBecause the function has a syntax error and does not run
DBecause <code>num</code> is declared inside <code>main</code> and is not accessible
Attempts:
2 left
💡 Hint

Think about how Go passes arguments to functions by default.

📝 Syntax
advanced
2:00remaining
Which option correctly declares a function that takes a pointer to int in Go?

Choose the correct Go function signature that accepts a pointer to an int.

Afunc update(x *int) {}
Bfunc update(*int x) {}
Cfunc update(int *x) {}
Dfunc update(x int*) {}
Attempts:
2 left
💡 Hint

In Go, the pointer symbol * goes before the type, not the variable name.

🚀 Application
expert
2:00remaining
How many items are in the slice after this function modifies it via pointer?

Consider this Go code that appends to a slice via a pointer. How many elements does the slice have after calling appendValue?

Go
package main
import "fmt"

func appendValue(s *[]int, v int) {
    *s = append(*s, v)
}

func main() {
    nums := []int{1, 2, 3}
    appendValue(&nums, 4)
    fmt.Println(len(nums))
}
A3
BCompilation error
C0
D4
Attempts:
2 left
💡 Hint

Appending to a slice inside a function requires updating the original slice via pointer.