函数
函数声明
Go
func function_name(arguments) [function_result_value] {
...
}
函数参数
固定长度的参数
- 如果函数参数的类型都一样可以只在最后一个参数后面写类型
Go
// 如果参数的类型都一样可以只在最后一个参数后面写类型
func fixedLengthArgs(a, b int) int {
return a + b
}
func main() {
sum := fixedLengthArgs(2, 6)
fmt.Println(sum) // 8
}
- 前两个参数的类型一样,第三个参数是另外的类型
Go
func fixedLengthArgs(a, b int, c string) int {
fmt.Println(c)
return a + b
}
func main() {
sum := fixedLengthArgs(2, 6, "张环")
fmt.Println(sum) // 8
}
不固定长度,多个参数类型一致
- 参数类型前面加
...
表示一个切片
,用来接收调用者传入的参数
示例
Go
func moreAargs(names ...string) {
for index, value := range names {
fmt.Printf("names[%d]=%s\n", index, value)
}
// names[0]=张环
// names[1]=李朗
// names[2]=杨方
// names[3]=仁阔
// names[4]=沈韬
// names[5]=肖豹
}
func main() {
moreAargs("张环", "李朗", "杨方", "仁阔","沈韬", "肖豹")
}
WARNING
如果函数下有其他类型的参数,这些参数必须放在参数列表的前面
,切片
必须放在最后
示例
Go
func moreAargs(age int, isBoss bool, names ...string) {
fmt.Println("age is", age) // age is 22
fmt.Println("isBoss is", isBoss) // isBoss is true
for index, value := range names {
fmt.Printf("names[%d]=%s\n", index, value)
}
// names[0]=张环
// names[1]=李朗
// names[2]=杨方
// names[3]=仁阔
// names[4]=沈韬
// names[5]=肖豹
}
func main() {
moreAargs(22, true, "张环", "李朗", "杨方", "仁阔","沈韬", "肖豹")
}
不固定长度,参数类型不一致
- 传多个参数的类型都不一样,可以指定类型为
...interface{}
,然后再遍历
示例
Go
func differentTpyeArgs(arguments ...interface{}) {
for index, value := range arguments {
fmt.Printf("第%d个参数的类型为%T\n", index + 1, value)
}
// 第1个参数的类型为string
// 第2个参数的类型为int
// 第3个参数的类型为float64
// 第4个参数的类型为bool
}
func main() {
differentTpyeArgs("燕双鹰", 22, 3.1415926, true)
}
解序列
- 使用
...
来解序列,能将函数的可变参数(即切片)一个一个取出来,例如切片的append方法
Go
func append(slice []Type, elems ...Type) []Type
示例
Go
func splitArgs() {
names := []string{"张环", "李朗"}
// 添加元素之前names为 [张环 李朗]
fmt.Println("添加元素之前names为", names)
names = append(names, []string{"沈韬", "肖豹", "杨方", "仁阔"}...)
// 添加元素之后names为 [张环 李朗 沈韬 肖豹 杨方 仁阔]
fmt.Println("添加元素之后names为", names)
}
示例
Go
func splitArgs(args ...string) {
for index, value := range args {
fmt.Printf("第%d个参数%s\n", index + 1, value)
}
// 第1个参数沈韬
// 第2个参数肖
// 第3个参数杨方
// 第4个参数仁阔
}
func main() {
splitArgs([]string{"沈韬", "肖豹", "杨方", "仁阔"}...)
}
函数返回值
一个返回值
示例
Go
func sum(a, b int) int {
return a + b
}
func main() {
increment_value := sum(2, 6)
fmt.Println(increment_value) // 8
}
多个返回值
Go
func multiReturnVal(a, b int) (int, bool) {
return a + b, a > b
}
func main() {
increment_value, isLarge := multiReturnVal(2, 6)
fmt.Println(increment_value, isLarge) // 8 false
}
返回值命名
Go
func namesReturnValue(a, b int) (increment int, isLarge bool) {
// 返回值已经声明过了,直接可以直接使用=,不再使用:=
increment = a + b
isLarge = a > b
return
}
func main() {
increment_value, isLarge := namesReturnValue(2, 6)
fmt.Println(increment_value, isLarge) // 8 false
}