golang-函数总结

126 阅读1分钟

1、变参 本质是slice 只能有一个,且必须是最后一个 

func test(s string, n...int)string 

使用slice对象作为变参,必须展开

 s:=[]int{1,2,3}
test("sum:", s...) 

2、返回值 不能用容器对象接收多返回值。只能用多个变量,或_忽略 多返回值可直接作为其它函数调用实参 

func add(x, y int)int 
func test()(int, int)
add(test()) 

命名返回参数, 可看做与形参类似的局部变量,最后由return隐式返回 

func add(x, y int)(z int){
   z=x+y
   return 
} 

命名返回参数允许defer延迟调用通过闭包读取与修改 

// add(1, 2) = 103func add(x, y int)(z int){   defer func(){      z+=100   }()   z=x+y   return }// (z=z+200)->(call defer)->(ret)func add1(x, y int)(z int){   defer func(){      print(z)   }()   z= x+y    return z+200}

4、匿名函数 匿名函数可以赋值给变量,作为结构字段,或者在channel里传达

fn := func(){print("hello wordl"}
fn()
//
fns := [](func(x int) int){
   func(x int) int {return x+1},
   func(x int) int{return x+2},
}
//
d := struct{
    fn func()string
}{
    fn: func()string{return "hello,world"}
}
//
fc := make(chan func()string, 2)
fc<-func() string{return "hello, world"}
print((<-fn)())

5、延迟调用 

defer用于注册延迟调用 直到ret前被执行 一般用于释放资源,错误处理 多个defer注册 FILO次序执行。

函数或某个延迟调用发生错误,调用依旧会被执行 panic在defer中未被捕获 逐步往外传递 最终中止进程 

任何未捕获的错误都会沿调用堆栈向外传递