官术网_书友最值得收藏!

Function

Functions are defined with the func keyword. Functions can have multiple parameters. All parameters are positional and there are no named parameters. Go supports variadic parameters allowing for an unknown number of parameters. Functions are first-class citizens in Go, and can be used anonymously and returned as a variable. Go also supports multiple return values from a function. The underscore can be used to ignore a return variable.

All of these examples are demonstrated in the following code source:

package main

import "fmt"

// Function with no parameters
func sayHello() {
fmt.Println("Hello.")
}

// Function with one parameter
func greet(name string) {
fmt.Printf("Hello, %s.\n", name)
}

// Function with multiple params of same type
func greetCustom(name, greeting string) {
fmt.Printf("%s, %s.\n", greeting, name)
}

// Variadic parameters, unlimited parameters
func addAll(numbers ...int) int {
sum := 0
for _, number := range numbers {
sum += number
}
return sum
}

// Function with multiple return values
// Multiple values encapsulated by parenthesis
func checkStatus() (int, error) {
return 200, nil
}

// Define a type as a function so it can be used
// as a return type
type greeterFunc func(string)

// Generate and return a function
func generateGreetFunc(greeting string) greeterFunc {
return func(name string) {
fmt.Printf("%s, %s.\n", greeting, name)
}
}

func main() {
sayHello()
greet("NanoDano")
greetCustom("NanoDano", "Hi")
fmt.Println(addAll(4, 5, 2, 3, 9))

russianGreet := generateGreetFunc("Привет")
russianGreet("NanoDano")

statusCode, err := checkStatus()
fmt.Println(statusCode, err)
}
主站蜘蛛池模板: 弥勒县| 吉木乃县| 德安县| 平山县| 天津市| 北辰区| 巴东县| 长顺县| 福贡县| 永嘉县| 赤水市| 遵化市| 友谊县| 淮滨县| 化州市| 清丰县| 宿松县| 调兵山市| 博兴县| 永修县| 手游| 万山特区| 连城县| 江源县| 邢台市| 泰宁县| 海宁市| 庆阳市| 保定市| 东乡县| 祁连县| 定陶县| 当雄县| 东乌珠穆沁旗| 司法| 淮安市| 邵阳县| 府谷县| 区。| 黑河市| 潜江市|