0
0
Goprogramming~20 mins

Value receivers in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Value Receiver Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
ACompilation error
B6
C0
D5
Attempts:
2 left
💡 Hint
Think about whether the method changes the original struct or a copy.
Predict Output
intermediate
2: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)
}
A5
B10
C0
DRuntime panic
Attempts:
2 left
💡 Hint
Does the Move method change the original Point or a copy?
🔧 Debug
advanced
2: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) }
ABecause Update has a value receiver and modifies a copy, not the original struct.
BBecause the struct Data is immutable in Go.
CBecause the Update method is missing a pointer receiver syntax.
DBecause the field value is unexported and cannot be changed.
Attempts:
2 left
💡 Hint
Think about how value receivers work with struct copies.
📝 Syntax
advanced
2: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.
A
func (c Counter) Increment() {
    c.count = c.count + 1
}
B
func (c *Counter) Increment() {
    c.count++
}
C
func Increment(c Counter) {
    c.count++
}
D
func (c Counter) Increment() {
    c.count += 1
}
Attempts:
2 left
💡 Hint
Which receiver type allows modifying the original struct?
🚀 Application
expert
3: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) }
A
1
1
B
2
3
C
1
3
D
2
4
Attempts:
2 left
💡 Hint
Remember which methods modify the original struct and which modify copies.