2023-09-25 golang函数

声明函数

  • 参数类型不同
func fn1(arg1 type,arg2 type) (output1 type,output2 type){
  return output1 ,output2 
}
  • 参数类型相同
func fn2(arg1 ,arg2 type) (output1 ,output2 type){
  return output1 ,output2 
}
  • 可变参数 ,arg2的类型为TS中的Array<string>
func fn3(arg1 int,arg2...string) (int,[]string){
  return arg1 ,arg2
}
  • 丢弃返回参数
// 接收多个返回参数,_丢弃当前数据
_,result :=fn3(1,"a","b")
  • 值传递,在调用函数时将实际参数复制一份传递到函数中,这样在函数中如果对参数进行修改,将不会影响到实际参数。
type aType struct {
    content string
}

a := aType{
  content : "a"
}

func fn4 (a aType) aType{
  a.content  = "aa"
  return a
}

result  := fn4(a)

fmt.Println(a, result)   // {a} {aa}
  • 引用传递,在调用函数时将实际参数的地址传递到函数中,那么在函数中对参数所进行的修改,将影响到实际参数。
type aType struct {
    content string
}

a := aType{
  content : "a"
}

func fn4 (a *aType) aType{
  a.content  = "aa"
  return *a
}

result  := fn4(&a)

fmt.Println(a, result)   // {aa} {aa}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容