Challenge - 5 Problems
Struct Pointer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of struct pointer field modification
What is the output of this Go program?
Go
package main import "fmt" type Person struct { Name string Age int } func main() { p := Person{"Alice", 30} ptr := &p ptr.Age = 31 fmt.Println(p.Age) }
Attempts:
2 left
💡 Hint
Remember that modifying a struct through its pointer changes the original struct.
✗ Incorrect
The pointer ptr points to p. Changing ptr.Age changes p.Age because ptr references p directly.
❓ Predict Output
intermediate2:00remaining
Output when assigning struct pointer to another variable
What will be printed by this Go program?
Go
package main import "fmt" type Point struct { X, Y int } func main() { p1 := &Point{X: 1, Y: 2} p2 := p1 p2.X = 10 fmt.Println(p1.X) }
Attempts:
2 left
💡 Hint
Both p1 and p2 point to the same struct in memory.
✗ Incorrect
p2 is assigned the pointer p1, so both point to the same Point struct. Changing p2.X changes p1.X.
🔧 Debug
advanced2:00remaining
Identify the runtime error in struct pointer usage
What error does this Go program produce when run?
Go
package main import "fmt" type Data struct { Value int } func main() { var d *Data d.Value = 5 fmt.Println(d.Value) }
Attempts:
2 left
💡 Hint
Check if the pointer d is initialized before accessing its fields.
✗ Incorrect
d is a nil pointer. Accessing d.Value causes a runtime panic due to nil pointer dereference.
🧠 Conceptual
advanced2:00remaining
Effect of passing struct pointer to a function
Consider this Go code snippet. What will be the output after calling updateAge(&p)?
Go
package main import "fmt" type Person struct { Age int } func updateAge(p *Person) { p.Age = 40 } func main() { p := Person{Age: 25} updateAge(&p) fmt.Println(p.Age) }
Attempts:
2 left
💡 Hint
Passing a pointer allows the function to modify the original struct.
✗ Incorrect
The function receives a pointer to p and sets p.Age to 40, modifying the original struct.
🔧 Debug
expert2:00remaining
Which option causes a runtime panic with struct pointers?
Given the struct type Node, which code snippet will cause a runtime panic?
Go
type Node struct {
Value int
Next *Node
}Attempts:
2 left
💡 Hint
Check if the pointer variable is initialized before accessing fields.
✗ Incorrect
Option A declares a nil pointer n and accesses n.Value, causing a runtime panic due to nil pointer dereference.