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

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)
}
主站蜘蛛池模板: 漠河县| 安平县| 张家界市| 大邑县| 宝坻区| 广河县| 中卫市| 贵南县| 墨江| 八宿县| 潜江市| 老河口市| 马鞍山市| 根河市| 安顺市| 浦江县| 金寨县| 邛崃市| 张掖市| 佳木斯市| 黄平县| 大竹县| 柯坪县| 湖南省| 即墨市| 平南县| 洮南市| 新兴县| 南充市| 招远市| 华宁县| 延吉市| 云和县| 车险| 江都市| 萨迦县| 会昌县| 北流市| 湾仔区| 慈溪市| 蚌埠市|