comparable Constraint क्या है
func Name[T comparable](a, b T) bool {
return a == b
}
Using comparable
built-in comparable interface से किसी type parameter को constrain करना गारंटी देता है कि == और != का उपयोग generic function के अंदर उस type की values पर किया जा सकता है।
उदाहरण: Using comparable
package main
import "fmt"
func Contains[T comparable](items []T, target T) bool {
for _, item := range items {
if item == target {
return true
}
}
return false
}
func main() {
fmt.Println(Contains([]int{1, 2, 3}, 2))
fmt.Println(Contains([]string{"a", "b"}, "c"))
}
Login to try C/C++/Java/PHP code in the editor
comparable for Map Keys
चूंकि Go map keys comparable होनी चाहिए, एक generic function जो अपने type parameter से keyed एक map बनाता है उसे comparable से उस parameter को constrain करना पड़ता है, नहीं तो compiler इसे reject कर देता है।
उदाहरण: comparable for Map Keys
package main
import "fmt"
func CountOccurrences[T comparable](items []T) map[T]int {
counts := make(map[T]int)
for _, item := range items {
counts[item]++
}
return counts
}
func main() {
fmt.Println(CountOccurrences([]string{"a", "b", "a", "c", "b", "a"}))
}
Login to try C/C++/Java/PHP code in the editor
comparable Does Not Mean Ordered
comparable सिर्फ equality checks (==, !=) की गारंटी देता है -- यह इस बारे में कुछ नहीं कहता कि values को < या > से ordered किया जा सकता है या नहीं, इसलिए एक generic sort या Max function को एक अलग, ज़्यादा specific constraint चाहिए।
उदाहरण: comparable Does Not Mean Ordered
package main
import "fmt"
func Unique[T comparable](items []T) []T {
seen := make(map[T]bool)
var result []T
for _, item := range items {
if !seen[item] {
seen[item] = true
result = append(result, item)
}
}
return result
}
func main() {
fmt.Println(Unique([]int{1, 2, 2, 3, 1, 4}))
}
Login to try C/C++/Java/PHP code in the editor
- किसी slice या map type parameter के साथ comparable उपयोग करने की कोशिश करना, क्योंकि slices और maps Go में खुद comparable नहीं हैं।
- यह भूल जाना कि comparable सिर्फ == और != काम करने की गारंटी देता है -- यह ordering (<, >) के बारे में कुछ नहीं कहता, जिसके लिए एक अलग constraint चाहिए।
- एक ऐसा generic function लिखना जिसे एक type को map key के रूप में चाहिए बिना इसे comparable से constrain किए, एक compile error का कारण बनते हुए।
- built-in comparable constraint किसी type parameter को == और != से compare होने देता है।
- comparable तब ज़रूरी है जब किसी type parameter को map key के रूप में उपयोग किया जाए।
- हर type comparable नहीं है -- slices, maps, और functions इसमें शामिल नहीं हैं।
- comparable ordering का मतलब नहीं रखता; < और > के लिए एक अलग constraint (जैसे Ordered) उपयोग करें।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: