Struct और Interface

Go Generics

Write one function or type that works with many types using type parameters.

  • मध्यम
  • 5 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • Type parameters
  • Constraints
  • Generic types
Sum[T Number]
Sum([]int{1, 2, 3})6
Sum([]float64{1.5, 2.5})4

One definition, many types

Generics let you write code once and use it with different types. A type parameter such as T, written in square brackets, stands for a type that is chosen where the code is used.

Number is a constraint: Sum accepts any type built on int or float64. Map has two type parameters, so it can turn a slice of one type into a slice of another. Stack[T] is a generic type, and Stack[string] is a stack of strings.

मुख्य बातें

  1. [T Number] limits T to numbers.
  2. any allows every type.
  3. Stack[string] is a stack of strings.

चलने योग्य Go उदाहरण

Go
कोड चलाएँ →
main.go
package main

import (
	"fmt"
	"strings"
)

type Number interface {
	~int | ~float64
}

func Sum[T Number](values []T) T {
	var total T
	for _, value := range values {
		total += value
	}
	return total
}

func Map[T, U any](items []T, convert func(T) U) []U {
	result := make([]U, 0, len(items))
	for _, item := range items {
		result = append(result, convert(item))
	}
	return result
}

type Stack[T any] struct {
	items []T
}

func (s *Stack[T]) Push(item T) { s.items = append(s.items, item) }

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() {
	fmt.Println(Sum([]int{1, 2, 3}), Sum([]float64{1.5, 2.5}))
	fmt.Println(Map([]int{1, 2, 3}, func(n int) string { return strings.Repeat("*", n) }))

	stack := &Stack[string]{}
	stack.Push("a")
	stack.Push("b")
	top, _ := stack.Pop()
	fmt.Println(top, len(stack.items))
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
6 4
[* ** ***]
b 1

अभ्यास

उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।

यह पाठ पूरा कर लिया?

अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।

चैलेंज से अभ्यास करें

इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।

सभी चैलेंज