1.函数的第一行定义了行数,接受什么样的输入,并提供什么样的输出,形参和返回结果,而这一行被称为函数签名。
2.通常结构 func 声明 + 函数名(形参 ...interface{}) +returnOne,returnTwo int 函数返回值,也可以是返回函数
比如: func Test()func()int{
var x = 0;
return func(){
x++;
return x;
}
}
3.返回多个值 :func test()(int,string){} //表示返回int 和string 多个值
4.定义不定参数: func test(number ...int){} //表示形参不确定数量,但类型必须是指定的int类型
5.返回具名返回值 func test()(x,y,z,j string ,k int){} // 返回具体的返回值名称 x,y,z,j
6.将函数作为值传递,本质go将函数视为了一种类型
func main(){
fn:=func(){fmt.Println("hello,world")}
anotherFunc(fn) //函数传递给函数anotherFunc
}
func anotherFunc(f func() string)string{
return f()
}
package main
import "fmt"
func main(){
fn:=func(){
fmt.Println("function called")
}
fn()
fmt.Println(anotherFunction(fn))
feedMe(1,0)
}
//函数为形参,函数形参需要声明骑返回类型,它可以是任何类型
func anotherFunction(f func() string)string{
return f()
}
type class struct{
name string
age int
}
//函数返回一个值
func add(x,y int)int{
return x+y
}
//函数返回多个值
func add1(x,y int,z string)(int,string){
return x+y, z+"ing"
}
//定义不定参数函数, 用三点...表示函数可以接受不确定的多个参数,但是参数类型必须统一
func number(numArr ...int)int{
total:=0
for _,v:=range numArr{
total +=v
}
return total
}
func getAllClass(t ...class) class {
return t[0]
}
//递归调用
func feedMe(x int,y int)int{
y = x+y
if y>=5{
fmt.Printf( "i'm full! I have y %d\n",y)
return y
}
fmt.Printf( "i'm still hungry I have y %d\n",y)
return feedMe(x,y)
}
在main中调用 feedME(1,0)
//不确定形参数量,统计他们
func number(numArr ...int)int{
total:=0
for _,v:=range numArr{
total +=v
}
return total
}
func main(){
return :=number(1,2,3,4)
fmt.Printf("%v\n",return)
}