Go के महत्वपूर्ण विषय

Go Closures and Function Values

Functions are values in Go: store them, pass them, return them, and let them remember variables.

  • मध्यम
  • 3 मिनट में पढ़ें
  • 1 चलाने योग्य उदाहरण
आप क्या सीखेंगे
  • Functions as values
  • Closures keep state
  • Passing a function
next := counter()
1next()
2next()
3next()
count lives on between calls.

A function that remembers

In Go a function is a value: you can store it in a variable, pass it to another function or return it. A closure is a function that keeps using variables from the place where it was created.

counter returns a function that remembers its own count between calls, and each call to counter creates a separate count. apply takes a function as a parameter. The function literal passed to apply reads bonus from main.

मुख्य बातें

  1. counter returns a function with its own count.
  2. Each call to counter starts a new count.
  3. A function literal can use variables around it.

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

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

import "fmt"

func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

func apply(values []int, transform func(int) int) []int {
	result := make([]int, len(values))
	for i, value := range values {
		result[i] = transform(value)
	}
	return result
}

func main() {
	next := counter()
	fmt.Println(next(), next(), next())

	other := counter() // a separate count
	fmt.Println(other())

	bonus := 10
	fmt.Println(apply([]int{1, 2, 3}, func(n int) int { return n*2 + bonus }))
}
इस उदाहरण के लिए Run बटन बनाएँ कोड चलाने का परिणाम
1 2 3
1
[12 14 16]

अभ्यास

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

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

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

अगला: JSON Encoding and Decoding →

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

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

सभी चैलेंज