0
0
Goprogramming~20 mins

Passing values vs pointers in Go - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of Passing Values and Pointers in Go
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of modifying a struct passed by value
What is the output of this Go program?
Go
package main
import "fmt"
type Point struct {
  X, Y int
}
func move(p Point) {
  p.X = 10
  p.Y = 20
}
func main() {
  pt := Point{1, 2}
  move(pt)
  fmt.Println(pt)
}
A{1 2}
B{10 20}
CCompilation error
D{0 0}
Attempts:
2 left
💡 Hint
Think about whether the function changes the original struct or a copy.
Predict Output
intermediate
2:00remaining
Output of modifying a struct passed by pointer
What is the output of this Go program?
Go
package main
import "fmt"
type Point struct {
  X, Y int
}
func move(p *Point) {
  p.X = 10
  p.Y = 20
}
func main() {
  pt := Point{1, 2}
  move(&pt)
  fmt.Println(pt)
}
A{10 20}
B{0 0}
CCompilation error
D{1 2}
Attempts:
2 left
💡 Hint
Check if the function receives a pointer and modifies the original struct.
Predict Output
advanced
2:00remaining
Effect of pointer vs value on slice modification
What is the output of this Go program?
Go
package main
import "fmt"
func modifySlice(s []int) {
  s[0] = 100
  s = append(s, 200)
}
func main() {
  slice := []int{1, 2, 3}
  modifySlice(slice)
  fmt.Println(slice)
}
A[100 2 3 200]
B[100 2 3]
C[1 2 3]
DRuntime panic
Attempts:
2 left
💡 Hint
Remember slices are references but append may create a new underlying array.
Predict Output
advanced
2:00remaining
Output when passing map by value and modifying it
What is the output of this Go program?
Go
package main
import "fmt"
func modifyMap(m map[string]int) {
  m["a"] = 100
  m = make(map[string]int)
  m["b"] = 200
}
func main() {
  myMap := map[string]int{"a": 1}
  modifyMap(myMap)
  fmt.Println(myMap)
}
Amap[a:1]
Bmap[b:200]
Cmap[a:100]
DCompilation error
Attempts:
2 left
💡 Hint
Maps are reference types in Go. Changes to the map inside the function affect the original map.
🧠 Conceptual
expert
3:00remaining
Understanding pointer semantics with interface values
Consider this Go code snippet. What will be printed? package main import "fmt" type Data struct { Value int } func modify(d interface{}) { switch v := d.(type) { case *Data: v.Value = 42 case Data: v.Value = 42 } } func main() { d1 := Data{1} d2 := &Data{1} modify(d1) modify(d2) fmt.Println(d1.Value, d2.Value) }
A42 42
BCompilation error
C42 1
D1 42
Attempts:
2 left
💡 Hint
Think about whether the modify function changes the original data or a copy depending on the type assertion.