new() Function का उपयोग
In this page:
p := new(type) // *type pointing to zero value
Using new() for a Basic Type
new(T) type T की एक value के लिए memory allocate करता है, इसे zero करता है, और इसका एक pointer (*T) return करता है -- तब उपयोगी जब आपको address लेने के लिए किसी मौजूदा variable के बिना एक fresh zero value का pointer चाहिए।
उदाहरण: Using new() for a Basic Type
package main
import "fmt"
func main() {
p := new(int)
fmt.Println(*p) // zero value: 0
*p = 42
fmt.Println(*p)
}
Login to try C/C++/Java/PHP code in the editor
new() with a Struct
new(Struct) एक zero-valued struct का pointer return करता है, functionally &Struct{} जैसा लेकिन बिना inline कोई initial field values सेट करने के option के।
उदाहरण: new() with a Struct
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// Define a struct type named Point
type Point struct {
X, Y int
}
// main is where the program starts running
func main() {
// Short declaration: create p and infer the type
p := new(Point)
p.X = 5
p.Y = 10
// Print the values followed by a newline
fmt.Println(p)
}
Login to try C/C++/Java/PHP code in the editor
new() vs make()
new() और make() को मिलाना आसान है: new(T) किसी भी type के लिए काम करता है और zeroed memory का एक pointer return करता है, जबकि make() सिर्फ slices, maps, और channels पर काम करता है, और उस type की एक initialized (zeroed-and-pointed-to नहीं) value खुद return करता है, pointer नहीं।
उदाहरण: new() vs make()
package main
import "fmt"
func main() {
p := new([]int) // *[]int pointing to a nil slice
s := make([]int, 3) // []int, ready to use with length 3
fmt.Println(*p, s)
}
Login to try C/C++/Java/PHP code in the editor
- new(T), जो zeroed T की ओर point करता *T return करता है, को make() के साथ confuse करना, जो सिर्फ slices/maps/channels के लिए है और pointer return नहीं करता।
- structs के लिए आदत से new() उपयोग करना जब &Type{} वाला एक struct literal ज़्यादा idiomatic है और initial fields सेट करने देता है।
- यह उम्मीद करना कि new() कोई custom initialization logic चलाएगा -- यह बिल्कुल सिर्फ memory zero करता है, और कुछ नहीं।
- new(T) किसी T के लिए zeroed memory allocate करता है और उसकी ओर point करता *T return करता है।
- new() किसी भी type के लिए काम करता है, लेकिन सबसे आम तौर पर basic types या simple structs के साथ दिखता है।
- structs के लिए new(Type) से &Type{} को आमतौर पर प्राथमिकता दी जाती है, क्योंकि यह initial field values सेट करने देता है।
- make() एक अलग builtin है, जो specifically slices, maps, और channels के लिए रखा गया है।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: