Value receiver
- Go course
- Beginner
- Lesson 77/90
- 4 min
Learn read-only methods with a value receiver.
Value receivers
A value receiver means the method works on a copy of the receiver; the method can't change it. This is a clear guarantee for read-only computations:
type Para struct{ Kurus int64 }
func (p Para) String() string {
return fmt.Sprintf("%d,%02d TL", p.Kurus/100, p.Kurus%100)
}
func (p Para) Ekle(q Para) Para {
return Para{p.Kurus + q.Kurus} // returns a new value
}Immutable value types
time.Time in the standard library is an example of this approach: t.Add(time.Hour) doesn't change t but returns a new time. Immutable types can be shared safely in concurrent code and are less error-prone. A value receiver can also be called through both a value and a pointer: (&p).String() works too.
Practice Money type
Write the Para type above with its String() and Ekle methods. For a := Para{1250} and b := a.Ekle(Para{375}), print a and b (String() is used).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Para struct{ Kurus int64 }
func (p Para) String() string {
return fmt.Sprintf("%d,%02d TL", p.Kurus/100, p.Kurus%100)
}
func (p Para) Ekle(q Para) Para {
return Para{p.Kurus + q.Kurus}
}
func main() {
a := Para{1250}
b := a.Ekle(Para{375})
fmt.Println(a, b)
}Expected output
12,50 TL 16,25 TL
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 After <code>a := Para{150}; b := a.Ekle(Para{50})</code>, what is <code>a.Kurus</code>?
- 200
- 50
- 0
- 150 Correct answer
Explanation: Ekle has a value receiver and returns a new Para; a stays the same and b becomes 200.
2 Return a new value
func (p Para) Ekle(q Para) Para {
____ Para{p.Kurus + q.Kurus}
}
func (p Para) Ekle(q Para) Para {
return Para{p.Kurus + q.Kurus}
}
Explanation: A value-receiver method returns its result as a new value.
3 Receiver kind and property
| Term | Meaning |
|---|---|
Value receiver |
Works on a copy |
Pointer receiver |
Changes the original |
time.Time.Add |
Returns a new value |
String() string |
Print format |