2

Go 函数

 2 years ago
source link: https://wnanbei.github.io/post/go-%E5%87%BD%E6%95%B0/
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.
neoserver,ios ssh client
Go语法

Go 函数

2019-01-01

阅读时长: 1 分钟

除了 main()init() 函数外,其它所有类型的函数都可以有参数与返回值。

函数参数、返回值以及它们的类型被统称为函数签名。

func find(num1 int, num2 int) {}
func find(num1, num2 int) {}

使用 ... 声明可变参数。

  • 可变参数只能放在参数列表的最末尾:
func find(num int, nums ...int){
    ...
}

声明后,可以在调用函数时传入任意数量的参数

find(89, 89, 90, 95)
find(45, 56, 67, 45, 90, 109)
find(87)

在函数中接收的nums被接收为一个切片。

如果希望将一个切片作为可变参数传入函数,则需要在传参的时候加上 ...

nums := []int{89, 90, 95}
find(89, nums...)

命名返回值

在声明函数时可以为其返回值命名。

命名了返回值后,可以认为这些值在函数第一行就已被声明为变量。

func rectProps(length, width float64)(area, perimeter float64) {  
    area = length * width
    perimeter = (length + width) * 2
    return // 不需要明确指定返回值,默认返回 area, perimeter 的值
}

在函数中,perimeter 不需要再次声明了。而且在 return 返回时,不再需要指定返回哪些变量,函数将自动把命名的返回值返回。

func(x, y int) int { return x + y }

这样的函数不能够独立存在,编译器会返回错误:non-declaration statement outside function body

但可以被赋值于某个变量,即保存函数的地址到变量中:

fplus := func(x, y int) int { return x + y }
fplus(3,4)

或者也可以直接对匿名函数进行调用:

func(x, y int) int { return x + y } (3, 4)

Go

Licensed under MIT License

最后更新于 2021-11-09 23:34:24


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK