Go की मूल बातें
Go Functions and Multiple Return Values
Functions in Go can return several values. Learn the result-and-error pattern and variadic parameters.
आप क्या सीखेंगे
- Parameters and results
- Returning a value and an error
- Variadic functions
divide(a, b)
divide(10, 4)2.5, nildivide(1, 0)0, "cannot divide by zero"A result and an error
A function groups code under a name. Go functions can return several values, and the usual pattern is to return a result together with an error.
divide returns the result and an error; nil means there was no error. The underscore ignores a value you do not need. numbers ...int accepts any number of integers, and the named result total is returned by the bare return.
मुख्य बातें
- A function can return more than one value.
- nil means there was no error.
- _ ignores a value you do not need.
चलने योग्य Go उदाहरण
main.go
package main
import (
"errors"
"fmt"
)
func area(width, height int) int {
return width * height
}
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("cannot divide by zero")
}
return a / b, nil
}
func sum(numbers ...int) (total int) {
for _, n := range numbers {
total += n
}
return
}
func main() {
fmt.Println(area(4, 5))
if result, err := divide(10, 4); err == nil {
fmt.Println(result)
}
_, err := divide(1, 0)
fmt.Println(err)
fmt.Println(sum(1, 2, 3, 4))
}
20
2.5
cannot divide by zero
10अभ्यास
उदाहरण को ऑनलाइन कंपाइलर में खोलें, कोई मान बदलें या एक पंक्ति जोड़ें, और चलाने से पहले आउटपुट का अनुमान लगाएँ। फिर कोड में जान-बूझकर गलती करें और कंपाइलर का संदेश पढ़ें।
यह पाठ पूरा कर लिया?
अपनी प्रगति ट्रैक करने के लिए इसे सीखा हुआ मार्क करें।
आपकी प्रगति इस ब्राउज़र में सेव है इसे हर डिवाइस पर रखने के लिए साइन इन करें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
- Largest of Three Pick the largest of three numbers without a built-in max. आसान
- Celsius to Fahrenheit Convert a temperature from Celsius to Fahrenheit. आसान