Type की Constraints
In this page:
type Constraint interface {
~int | ~float64 | string
}
func Name[T Constraint](param T) T {
// body
}
Defining a Constraint Interface
एक type constraint एक interface के रूप में लिखा जाता है, और किसी generic function का type parameter इसे reference करता है यह सीमित करने के लिए कि कौन सी concrete types legal हैं -- function के अंदर उपलब्ध operations को constraint द्वारा guaranteed तक सीमित करते हुए।
उदाहरण: Defining a Constraint Interface
package main
import "fmt"
type Ordered interface {
int | int64 | float64 | string
}
func Max[T Ordered](a, b T) T {
if a > b {
return a
}
return b
}
func main() {
fmt.Println(Max(3, 9))
fmt.Println(Max("apple", "banana"))
}
Login to try C/C++/Java/PHP code in the editor
Constraints with Method Requirements
एक साधारण interface की तरह, एक constraint allowed types के एक union के बजाय (या साथ) specific methods मांग सकता है, generic code को type parameter की किसी भी value पर वे methods call करने देते हुए।
उदाहरण: Constraints with Method Requirements
package main
import "fmt"
type Stringer interface {
String() string
}
func PrintAll[T Stringer](items []T) {
for _, item := range items {
fmt.Println(item.String())
}
}
type Item struct {
Name string
}
func (i Item) String() string { return "Item: " + i.Name }
func main() {
PrintAll([]Item{{Name: "Pen"}, {Name: "Book"}})
}
Login to try C/C++/Java/PHP code in the editor
Combining Unions and Methods
एक constraint interface एक type union को method requirements के साथ combine कर सकता है, बिल्कुल control देते हुए कि कौन सी types स्वीकार्य हैं और generic code उन पर कौन से operations perform कर सकता है।
उदाहरण: Combining Unions and Methods
package main
import "fmt"
type Numeric interface {
~int | ~float64
}
func Average[T Numeric](nums []T) float64 {
var total T
for _, n := range nums {
total += n
}
return float64(total) / float64(len(nums))
}
func main() {
fmt.Println(Average([]int{2, 4, 6}))
}
Login to try C/C++/Java/PHP code in the editor
- एक constraint interface define करना लेकिन यह भूल जाना कि types का एक union (int | float64) ही असल में arithmetic operators की अनुमति देता है, सिर्फ method requirements नहीं।
- किसी struct के अपने methods को एक explicit interface declare किए बिना एक implicit constraint के रूप में उपयोग करने की कोशिश करना।
- किसी constraint को ज़रूरत से ज़्यादा जटिल बनाना जब built-in any या standard library का constraints/cmp package पहले से ज़रूरत पूरी करता हो।
- एक constraint एक interface है जो सीमित करता है कि किसी type parameter के लिए कौन सी types substitute की जा सकती हैं।
- types का एक union, जैसे int | float64, + या < जैसे operators की अनुमति देने के लिए एक constraint में उपयोग होता है।
- built-in comparable constraint किसी type parameter पर == और != की अनुमति देता है।
- Constraints किसी भी regular interface की तरह specific methods भी मांग सकते हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: