Value और Pointer Receivers में अंतर
In this page:
func (r Type) valueMethod() {
// receives a copy
}
func (r *Type) pointerMethod() {
// can modify r
}
Value Receivers Copy
एक value receiver वाला method struct की अपनी independent copy पाता है -- इसके अंदर किए कोई भी बदलाव method के return होते ही अदृश्य हो जाते हैं, क्योंकि वे copy के साथ हुए, original के साथ नहीं।
उदाहरण: Value Receivers Copy
package main
import "fmt"
type Counter struct {
Value int
}
func (c Counter) IncrementValue() {
c.Value++ // modifies the copy only
}
func main() {
c := Counter{Value: 0}
c.IncrementValue()
fmt.Println("still:", c.Value)
}
Login to try C/C++/Java/PHP code in the editor
Pointer Receivers Mutate
एक pointer receiver वाला method इसके address के ज़रिए सीधे original struct पर operate करता है, इसलिए method के अंदर किए बदलाव इसके return होने के बाद caller को दिखाई देते हैं।
उदाहरण: Pointer Receivers Mutate
package main
import "fmt"
type Counter struct {
Value int
}
func (c *Counter) IncrementValue() {
c.Value++ // modifies the original
}
func main() {
c := Counter{Value: 0}
c.IncrementValue()
fmt.Println("now:", c.Value)
}
Login to try C/C++/Java/PHP code in the editor
Automatic Addressing
Go आपको किसी साधारण (addressable) struct value पर सीधे एक pointer-receiver method call करने देता है, जैसे c.IncrementValue(), पीछे अपने आप इसका address लेते हुए -- आपको खुद (&c).IncrementValue() लिखने की ज़रूरत नहीं।
उदाहरण: Automatic Addressing
package main
import "fmt"
type Account struct {
Balance float64
}
func (a *Account) Deposit(amount float64) {
a.Balance += amount
}
func main() {
acc := Account{Balance: 100}
acc.Deposit(50) // Go automatically does (&acc).Deposit(50)
fmt.Println(acc.Balance)
}
Login to try C/C++/Java/PHP code in the editor
- struct modify करने वाले method के लिए एक value receiver उपयोग करना, फिर यह confuse होना कि बदलाव method के बाहर क्यों बना नहीं रहता।
- किसी type के methods में असंगत रूप से value और pointer receivers मिलाना, जो किसी interface implementation को समझना ज़्यादा मुश्किल बना सकता है।
- छोटे structs पर सिर्फ आदत से एक pointer receiver उपयोग करना जहां एक value receiver सरल और उतना ही efficient होता।
- एक value receiver, func (t Type) M(), value की एक copy पर operate करता है।
- एक pointer receiver, func (t *Type) M(), original value पर operate करता है और इसे modify कर सकता है।
- Go किसी addressable value पर pointer-receiver method call करते समय आपके लिए अपने आप address लेता है।
- pointer receivers उपयोग करें जब method को receiver modify करना हो या struct बड़ा हो।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: