函数格式:
func foo( a int, b string )
参数类型的简写形式:
在参数列表中,如有多个参数变量,则以逗号分隔;如果相邻变量是同类型,则可以将类型省略
unc add(a, b int) int { return a + b }
函数的多返回值:
1) 同一种类型返回值
func typedTwoValues() (int, int) { return 1, 2 } a, b := typedTwoValues() fmt.Println(a, b)
2) 带有变量名的返回值
命名的返回值变量的默认值为类型的默认值,即数值为 0,字符串为空字符串,布尔为 false、指针为 nil 等。
func namedRetValues() (a, b int) { a = 1 b = 2 return }
函数变量:
在 Go 语言中,函数也是一种类型,可以和其他类型一样被保存在变量中。下面的代码定义了一个函数变量 f,并将一个函数名 fire() 赋给函数变量 f,这样调用函数变量 f 时,实际调用的就是 fire() 函数,代码如下:
func fire() { fmt.Println("fire") } func main() { var f func() f = fire f() }
匿名函数:
匿名函数定义格式:
func(参数列表)(返回参数列表){
函数体
}
匿名函数的两种调用方式:
第一:
func(data int) { fmt.Println("hello", data) }(100)
第二:
// 将匿名函数体保存到f()中 f := func(data int) { fmt.Println("hello", data) } // 使用f()调用 f(100)
变参函数:
参数类型指定:
// 定义一个函数, 参数数量为0~n, 类型约束为字符串 func joinStrings(slist ...string) string { } func main() { fmt.Println(joinStrings("pig ", "and", " rat")) }
参数类型不指定:
func printTypeValue(slist ...interface{}) string { return b.String() } func main() { fmt.Println(printTypeValue(100, "str", true)) }