函数是go语言编程的核心,这里将通过以下几个不同的例子来了解和学习函数的使用。
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.html
这里实现一个函数,它接受两个int
类型参数并将它们的和作为一个int
返回。
在go编程中需要显式返回,即它不会自动返回最后一个表达式的值。
当有多个相同类型的连续参数时,可以省略类型参数的类型名称,直到声明该类型的最后一个参数。
使用name(args)
调用函数,正如所期望的调用方式那样。
go函数还有几个其他功能。一个是多个返回值,在接下来实现中我们来看看。
functions.go
的完整代码如下所示 -
package main
import "fmt"
// here's a function that takes two `int`s and returns
// their sum as an `int`.
func plus(a int, b int) int {
// go requires explicit returns, i.e. it won't
// automatically return the value of the last
// expression.
return a + b
}
// when you have multiple consecutive parameters of
// the same type, you may omit the type name for the
// like-typed parameters up to the final parameter that
// declares the type.
func plusplus(a, b, c int) int {
return a + b + c
}
func main() {
// call a function just as you'd expect, with
// `name(args)`.
res := plus(1, 2)
fmt.println("1+2 =", res)
res = plusplus(1, 2, 3)
fmt.println("1+2+3 =", res)
}
执行上面代码,将得到以下输出结果 -
f:\worksp\golang>go run functions.go
1+2 = 3
1+2+3 = 6