Type के Parameters
In this page:
func Name[T any](param T) T {
// body
}
func Name[K comparable, V any](m map[K]V) {}
Declaring Type Parameters
किसी generic function के type parameters function name के ठीक बाद square brackets में list किए जाते हैं, हर एक को एक नाम और एक constraint दिया जाता है जो सीमित करता है कि कौन सी concrete types substitute होने की अनुमति है।
उदाहरण: Declaring Type Parameters
package main
import "fmt"
func Identity[T any](v T) T {
return v
}
func main() {
fmt.Println(Identity(42))
fmt.Println(Identity("hello"))
}
Login to try C/C++/Java/PHP code in the editor
Using Type Parameters in the Body
एक बार declared होने पर, एक type parameter को function के अंदर कहीं भी उपयोग किया जा सकता है जहां एक concrete type जाती -- local variables, slice elements, या return type के रूप में।
उदाहरण: Using Type Parameters in the Body
package main
import "fmt"
func Duplicate[T any](v T) []T {
return []T{v, v}
}
func main() {
fmt.Println(Duplicate(7))
fmt.Println(Duplicate("go"))
}
Login to try C/C++/Java/PHP code in the editor
Type Inference at Call Sites
Go आमतौर पर आपके पास किए arguments से किसी type parameter के लिए concrete type अपने आप पता लगा लेता है, इसलिए किसी generic function को ज़्यादातर calls बिल्कुल एक normal को call करने जैसी दिखती हैं, बिना किसी अतिरिक्त bracket syntax के।
उदाहरण: Type Inference at Call Sites
package main
import "fmt"
func Pair[T any](a, b T) [2]T {
return [2]T{a, b}
}
func main() {
fmt.Println(Pair(1, 2)) // T inferred as int
fmt.Println(Pair("a", "b")) // T inferred as string
}
Login to try C/C++/Java/PHP code in the editor
- यह भूल जाना कि type parameters square brackets [T Constraint] में जाते हैं, regular parameters की तरह parentheses में नहीं।
- एक bare, unconstrained type parameter (any) उपयोग करना और फिर इस पर + जैसे operators उपयोग करने की कोशिश करना, जो सिर्फ उस operator को support करने वाली constrained types के लिए काम करता है।
- असंबंधित generic functions में एक जैसा type parameter name T दोहराना और यह मान लेना कि वे मतलब share करते हैं -- हर declaration स्वतंत्र है।
- एक type parameter list किसी generic function के नाम और इसके regular parameters के बीच square brackets में दिखाई देती है।
- हर type parameter की एक constraint होती है जो specify करती है कि कौन सी types अनुमति है, जैसे [T any] या [T int | float64]।
- Type parameters कहीं भी उपयोग किए जा सकते हैं जहां आमतौर पर एक type दिखाई देती: parameter types, return types, या local variables।
- Go आमतौर पर arguments से type parameters infer करता है, इसलिए आपको call site पर शायद ही कभी इन्हें explicitly specify करने की ज़रूरत पड़े।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: