Generics परिचय
func FunctionName[T any](param T) T {
return param
}
FunctionName[int](value) // explicit type
FunctionName(value) // type inferred
Why Generics?
Generics से पहले, एक function लिखना जो []int और []string दोनों पर काम करे का मतलब था या तो function को हर type के लिए दोहराना या interface{} पर वापस जाना और compile-time type safety खोना।
Generics इसे हल करते हैं एक function definition को कई types में काम करने देकर जबकि compiler अब भी types जांचता है।
उदाहरण: Why Generics?
package main
import "fmt"
func PrintAll[T any](items []T) {
for _, item := range items {
fmt.Println(item)
}
}
func main() {
PrintAll([]int{1, 2, 3})
PrintAll([]string{"a", "b"})
}
Login to try C/C++/Java/PHP code in the editor
A Simple Generic Function
एक generic function अपने नाम के ठीक बाद square brackets में एक या ज़्यादा type parameters declare करता है, जिन्हें फिर function के signature और body में कहीं भी किसी दूसरे type की तरह उपयोग किया जा सकता है।
उदाहरण: A Simple Generic Function
package main
import "fmt"
func Max[T int | float64](a, b T) T {
if a > b {
return a
}
return b
}
func main() {
fmt.Println(Max(3, 7))
fmt.Println(Max(2.5, 1.1))
}
Login to try C/C++/Java/PHP code in the editor
Generics Are Still Type-Checked
भले ही generic code कई types के लिए एक बार लिखा जाता है, Go अब भी compile time पर हर instantiation को पूरी तरह type-check करता है -- किसी generic function को एक ऐसी type के साथ call करना जो इसके constraints satisfy नहीं करती एक compile error है, कोई runtime surprise नहीं।
उदाहरण: Generics Are Still Type-Checked
package main
import "fmt"
func First[T any](items []T) T {
return items[0]
}
func main() {
fmt.Println(First([]string{"go", "generics"}))
fmt.Println(First([]bool{true, false}))
}
Login to try C/C++/Java/PHP code in the editor
- यह मान लेना कि Go में शुरू से generics थे -- इन्हें सिर्फ Go 1.18 (2022) में जोड़ा गया, इसलिए पुराने code और tutorials अक्सर इन्हें पूरी तरह टालते हैं।
- हर function के लिए generics का सहारा लेना, भले ही एक साधारण interface या कुछ concrete-typed functions ज़्यादा सरल होते।
- यह भूल जाना कि type parameter को regular parameter list से पहले square brackets में declare होना चाहिए।
- Go 1.18 में जोड़े गए Generics, functions और types को कई types के साथ काम करने देते हैं जबकि type-safe रहते हुए।
- एक type parameter regular parameters से पहले square brackets में declared होता है, जैसे func Max[T int | float64](a, b T) T।
- Generics हर concrete type के लिए लगभग-एक-जैसा code दोहराने से बचाते हैं।
- Go अब भी generic code को compile time पर resolve करता है -- कोई runtime type-erasure surprise नहीं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: