Challenge - 5 Problems
Go Value Receiver Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of method with value receiver
What is the output of this Go program?
Go
package main import "fmt" type Counter struct { count int } func (c Counter) Increment() { c.count++ } func main() { c := Counter{count: 5} c.Increment() fmt.Println(c.count) }
Attempts:
2 left
💡 Hint
Think about whether the method changes the original struct or a copy.
✗ Incorrect
The method Increment has a value receiver, so it works on a copy of the struct. The original count remains unchanged, so the output is 5.
❓ Predict Output
intermediate2:00remaining
Effect of value receiver on struct field
What will this program print?
Go
package main import "fmt" type Point struct { x int } func (p Point) Move() { p.x = 10 } func main() { pt := Point{x: 5} pt.Move() fmt.Println(pt.x) }
Attempts:
2 left
💡 Hint
Does the Move method change the original Point or a copy?
✗ Incorrect
Move uses a value receiver, so it modifies a copy of pt. The original pt.x remains 5.
🔧 Debug
advanced2:00remaining
Why does this value receiver method not update the struct?
Consider this code snippet. Why does the field not update after calling Update()?
package main
import "fmt"
type Data struct {
value int
}
func (d Data) Update() {
d.value = 100
}
func main() {
data := Data{value: 50}
data.Update()
fmt.Println(data.value)
}
Attempts:
2 left
💡 Hint
Think about how value receivers work with struct copies.
✗ Incorrect
Value receivers get a copy of the struct, so changes inside Update do not affect the original data variable.
📝 Syntax
advanced2:00remaining
Identify the error in this value receiver method
Which option correctly fixes the syntax error in this method?
func (c Counter) Increment() {
c.count++
}
Assuming Counter is a struct with field count int.
Attempts:
2 left
💡 Hint
Which receiver type allows modifying the original struct?
✗ Incorrect
Only option B uses a pointer receiver, allowing the method to modify the original struct's field.
🚀 Application
expert3:00remaining
Predict the output with mixed value and pointer receivers
What is the output of this program?
package main
import "fmt"
type Number struct {
n int
}
func (num Number) AddOne() {
num.n++
}
func (num *Number) AddTwo() {
num.n += 2
}
func main() {
x := Number{n: 1}
x.AddOne()
fmt.Println(x.n)
x.AddTwo()
fmt.Println(x.n)
}
Attempts:
2 left
💡 Hint
Remember which methods modify the original struct and which modify copies.
✗ Incorrect
AddOne uses a value receiver, so it does not change x.n. AddTwo uses a pointer receiver, so it adds 2 to x.n.