← Back to Go Course | Chapter 12: Generics | Lesson 3 of 6

Generic Functions लिखना

एक generic function लिखना एक tool design करने जैसा है जो आपके दिए हर size के handle में अपनी grip adjust करे, बजाय हर handle size के लिए एक अलग tool बनाने के।
Syntax
go
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

markup
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}))
}

A Generic Filter Function

Generic functions higher-order functions के साथ भी अच्छी तरह काम करते हैं, जैसे एक Filter जो सिर्फ एक predicate से मेल खाते elements रखता है, chahe slice असल में कोई भी type रखे।

उदाहरण: A Generic Filter Function

markup
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)
}

Multiple Type Parameters

एक generic function एक से ज़्यादा type parameters declare कर सकता है, एक type की slice को एक अलग type की slice में convert करने वाले map-transform जैसे functions के लिए उपयोगी।

उदाहरण: Multiple Type Parameters

markup
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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. एक single generic Sum function के बजाय तीन लगभग-एक-जैसे functions (SumInts, SumFloats, ...) लिखना।
  2. ऐसे function पर एक अत्यधिक permissive constraint (any) उपयोग करना जिसे असल में arithmetic operators चाहिए, + उपयोग होने पर एक compile error का कारण बनते हुए।
  3. यह भूल जाना कि 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.