Generic Functions लिखना
func Name[T constraint](param T) T {
// body
}
result := Name[Type](arg)
result := Name(arg)
A Generic Sum Function
numbers की एक slice sum करने वाला एक function numeric types तक constrained एक type parameter के साथ एक बार लिखा जा सकता है, बजाय SumInts और SumFloats को अलग-अलग लिखने के।
उदाहरण: A Generic Sum Function
package main
import "fmt"
type Number interface {
int | float64
}
func Sum[T Number](nums []T) T {
var total T
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(Sum([]int{1, 2, 3}))
fmt.Println(Sum([]float64{1.5, 2.5}))
}
Login to try C/C++/Java/PHP code in the editor
A Generic Filter Function
Generic functions higher-order functions के साथ भी अच्छी तरह काम करते हैं, जैसे एक Filter जो सिर्फ एक predicate से मेल खाते elements रखता है, chahe slice असल में कोई भी type रखे।
उदाहरण: A Generic Filter Function
package main
import "fmt"
func Filter[T any](items []T, keep func(T) bool) []T {
var result []T
for _, item := range items {
if keep(item) {
result = append(result, item)
}
}
return result
}
func main() {
nums := []int{1, 2, 3, 4, 5, 6}
even := Filter(nums, func(n int) bool { return n%2 == 0 })
fmt.Println(even)
}
Login to try C/C++/Java/PHP code in the editor
Multiple Type Parameters
एक generic function एक से ज़्यादा type parameters declare कर सकता है, एक type की slice को एक अलग type की slice में convert करने वाले map-transform जैसे functions के लिए उपयोगी।
उदाहरण: Multiple Type Parameters
package main
import "fmt"
func Map[T, U any](items []T, f func(T) U) []U {
result := make([]U, len(items))
for i, item := range items {
result[i] = f(item)
}
return result
}
func main() {
nums := []int{1, 2, 3}
strs := Map(nums, func(n int) string {
return fmt.Sprintf("#%d", n)
})
fmt.Println(strs)
}
Login to try C/C++/Java/PHP code in the editor
- एक single generic Sum function के बजाय तीन लगभग-एक-जैसे functions (SumInts, SumFloats, ...) लिखना।
- ऐसे function पर एक अत्यधिक permissive constraint (any) उपयोग करना जिसे असल में arithmetic operators चाहिए, + उपयोग होने पर एक compile error का कारण बनते हुए।
- यह भूल जाना कि generic functions अब भी कई values return कर सकते हैं और सभी normal Go control flow उपयोग कर सकते हैं -- generics सिर्फ type parameter mechanism को प्रभावित करते हैं।
- एक generic function type parameters के साथ declared होता है, फिर उन parameters को किसी दूसरे type की तरह उपयोग करके एक बार implement किया जाता है।
- Constraints तय करते हैं कि function के अंदर किसी type parameter पर कौन से operators और methods valid हैं।
- Generic functions कई concrete-typed variants में लगभग-duplicate code खत्म करते हैं।
- Slices, maps, और दूसरी composite types सभी अपने element type के रूप में type parameters उपयोग कर सकती हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: