Generic Types क्या हैं
type Name[T any] struct {
field T
}
func (n *Name[T]) Method() T {
// body
}
value := Name[int]{}
Defining a Generic Struct
एक struct type अपने नाम के ठीक बाद square brackets में अपना खुद का type parameter declare कर सकता है, वही struct definition को इसके instantiate होने पर चुनी किसी भी element type के साथ काम करने देते हुए।
उदाहरण: Defining a Generic Struct
package main
import "fmt"
type Box[T any] struct {
Value T
}
func main() {
intBox := Box[int]{Value: 42}
strBox := Box[string]{Value: "hello"}
fmt.Println(intBox.Value, strBox.Value)
}
Login to try C/C++/Java/PHP code in the editor
Methods on Generic Types
किसी generic type पर एक method define करने के लिए इसके type parameter को method के receiver clause में दोहराना चाहिए, जिसके बाद parameter उस method के अंदर किसी दूसरे type जैसा व्यवहार करता है।
उदाहरण: Methods on Generic Types
package main
import "fmt"
type Stack[T any] struct {
items []T
}
func (s *Stack[T]) Push(v T) {
s.items = append(s.items, v)
}
func (s *Stack[T]) Pop() (T, bool) {
var zero T
if len(s.items) == 0 {
return zero, false
}
last := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return last, true
}
func main() {
s := &Stack[int]{}
s.Push(1)
s.Push(2)
v, _ := s.Pop()
fmt.Println(v)
}
Login to try C/C++/Java/PHP code in the editor
Instantiating a Generic Type
एक generic type का उपयोग square brackets में एक concrete type देकर किया जाता है, या तो explicitly (Stack[int]{}) या किसी constructor function के arguments से infer करते हुए।
उदाहरण: Instantiating a Generic Type
package main
import "fmt"
type Pair[T any] struct {
First, Second T
}
func NewPair[T any](a, b T) Pair[T] {
return Pair[T]{First: a, Second: b}
}
func main() {
p := NewPair(1, 2)
fmt.Println(p.First, p.Second)
}
Login to try C/C++/Java/PHP code in the editor
- यह भूल जाना कि किसी generic struct के type parameter को type instantiate होने पर specify (या infer) किया जाना चाहिए, जैसे Stack[int]{}।
- किसी generic type पर methods define करना बिना इसके type parameter को method के receiver में दोहराए, जो ज़रूरी syntax है।
- किसी generic type के एक instantiation में जो सिर्फ एक element type के लिए intended है उसमें कई असंबंधित concrete types मिलाने की कोशिश करना।
- एक struct (या दूसरा type) अपने खुद के type parameters declare कर सकता है, इसे एक generic type बनाते हुए।
- किसी generic type पर methods को receiver में type parameter दोहराना चाहिए, जैसे func (s *Stack[T]) Push(v T)।
- एक generic type एक concrete type देकर instantiate किया जाता है, जैसे Stack[int]{} या Stack[string]{}।
- Generic types stacks, queues, और linked lists जैसे reusable data structures के लिए आदर्श हैं।
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: