Pointer के Basics
In this page:
var p *type
p := &variable
What Is a Pointer?
एक pointer variable खुद value के बजाय किसी दूसरी value का memory address store करता है। Go में, किसी type T का pointer *T लिखा जाता है, और आप किसी मौजूदा value पर & (address-of) operator से एक पाते हैं।
उदाहरण: What Is a Pointer?
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create x and infer the type
x := 10
// Short declaration: create p and infer the type
p := &x
// Print the values followed by a newline
fmt.Println("value of x:", x)
// Print the values followed by a newline
fmt.Println("address stored in p:", p)
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing a Pointer
*p से dereferencing उस address पर stored असली value निकालती है जो एक pointer रखता है -- यह वह operation है जो कहता है 'इस address को follow करो और मुझे वहां जो है वह दो'।
उदाहरण: Dereferencing a Pointer
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create x and infer the type
x := 10
// Short declaration: create p and infer the type
p := &x
// Print the values followed by a newline
fmt.Println("dereferenced value:", *p)
}
Login to try C/C++/Java/PHP code in the editor
Pointers Enable Automatic Garbage Collection
C के विपरीत, Go आपके लिए memory manage करता है -- आप कभी manually किसी pointer की memory free नहीं करते। garbage collector track करता है कि कोई value अब किसी pointer के ज़रिए reachable नहीं है और इसे अपने आप वापस पा लेता है।
उदाहरण: Pointers Enable Automatic Garbage Collection
package main
import "fmt"
func newValue() *int {
v := 42 // safely escapes to the heap; Go's GC manages its lifetime
return &v
}
func main() {
p := newValue()
fmt.Println(*p)
}
Login to try C/C++/Java/PHP code in the editor
- & (address-of) को * (dereference) के साथ confuse करना -- & किसी value का pointer पाता है, * वह value पाता है जिस पर कोई pointer point करता है।
- यह मान लेना कि pointers को C की तरह manual memory management चाहिए -- Go का garbage collector memory free करना अपने आप handle करता है।
- किसी pointer variable को सीधे print करना और पहले इसे dereference करके value देखने के बजाय hexadecimal memory address देखकर confuse होना।
- एक pointer खुद value के बजाय उसका memory address रखता है।
- &x, x का address पाता है (एक pointer); *p वह value पाता है जिस पर pointer p point करता है।
- Go pointers garbage collected हैं -- C जैसा कोई manual malloc/free नहीं है।
- Pointers किसी function को caller का variable modify करने देने के लिए, या बड़ी values copy करने से बचने के लिए उपयोग होते हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: