49

golang函数的几个点

 5 years ago
source link: https://studygolang.com/articles/18152?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

命名函数与匿名函数

函数本质上都是匿名的,命名函数是特例

func A(a int) int {
  return 12
}
var A=func(a int) int {
  return 12
}

可变参数

可变参数必须放在最后面,本质是slice。再引用可变参数时,需要加上 ... 才行,如是

func A(a ...int) {
  Foo(a...)
}
func Foo(b ...int) {
  fmt.Println(b...)
}

命名的返回值

如果给返回值命名了,就可以直接操作返回值,并且也可以通过defer函数对它(它们)进行操作。

defer定义一个匿名函数,创建闭包,闭包对捕获的外部变量是以引用的方式进行访问。

如果是通过传参方式,还是会在defer执行的时候就对参数求值(这时候是值传递),我们这里讲的引用传递只针对捕获的外部变量。

方法与函数的转化

如果用面向对象的思路来讲,就是方法,如果按传统的面向过程的角度来说,就是函数。Go中可以很方便地将方法转化成函数,然后按照函数的方式来编写代码:

func CloseFile(f * File) error;
func (f * File) Close error;
var MyCloseFile = (*File).Close;

下面的三种用法都是等效的:

var f *File
f.Close()
CloseFile(f)
MyCloseFile(f)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK