[Golang]-3 函数、多返回值、变参、闭包、递归

// test01 project main.go
package main

import (
	"fmt"
)

// 单返回值的函数
func plus(a int, b int) int {
	// Go 需要明确的返回值
	return a + b
}

// (int, int) 在这个函数中标志着这个函数返回 2 个 int。
func vals() (int, int) {
	return 3, 7
}

// 可变参数函数。可以用任意数量的参数调用。例如,fmt.Println 是一个常见的变参函数。
// 这个函数使用任意数目的 int 作为参数。
func sum(nums ...int) {
	fmt.Print(nums, " ")
	total := 0
	for _, num := range nums {
		total += num
	}
	fmt.Println(total)
}

// Go 支持通过 闭包来使用 匿名函数。匿名函数在你想定义一个不需要命名的内联函数时是很实用的
// 这个 intSeq 函数返回另一个在 intSeq 函数体内定义的匿名函数。这个返回的函数使用闭包的方式 隐藏 变量 i。
func intSeq() func() int {
	i := 0
	return func() int {
		i += 1
		return i
	}
}

// 递归
func fact(n int) int {
	if n == 0 {
		return 1
	}
	return n * fact(n-1)
}

func main() {
	res := plus(1, 2)
	fmt.Println("1+2 =", res)

	// 通过多赋值 操作来使用这两个不同的返回值
	a, b := vals()
	fmt.Println(a)
	fmt.Println(b)

	// 如果你仅仅想返回值的一部分的话,你可以使用空白定义符 _
	_, c := vals()
	fmt.Println(c)

	// 变参调用
	sum(1, 2)
	sum(1, 2, 3)

	// 如果你的 slice 已经有了多个值,想把它们作为变参使用,你要这样调用 func(slice...)
	nums := []int{1, 2, 3, 4}
	sum(nums...)

        // 闭包
	// 我们调用 intSeq 函数,将返回值(也是一个函数)赋给nextInt。这个函数的值包含了自己的值 i,这样在每次调用 nextInt 时都会更新 i 的值。
	nextInt := intSeq()

	// 通过多次调用 nextInt 来看看闭包的效果。
	fmt.Println(nextInt())
	fmt.Println(nextInt())
	fmt.Println(nextInt())

	// 为了确认这个状态对于这个特定的函数是唯一的,我们重新创建并测试一下。
	newInts := intSeq()
	fmt.Println(newInts())
	fmt.Println(newInts())

	// 递归函数调用
	fmt.Println(fact(0))
	fmt.Println(fact(1))
	fmt.Println(fact(2))
	fmt.Println(fact(3))
	fmt.Println(fact(4))
	fmt.Println(fact(5))
	fmt.Println(fact(6))
	fmt.Println(fact(7))
}
输出
// 普通函数
1+2 = 3

// 多返回值
3
7
7

// 可变参数函数
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10

// 闭包
1
2
3
1
2

// 递归
1
1
2
6
24
120
720
5040

备注:

  • 闭包:是能够读取其他函数内部变量的函数;
  • 匿名函数:一个没有指定名称的函数。匿名函数的参数规则、作用域关系与有名函数是一样的;匿名函数的函数体通常应该是 一个表达式,该表达式必须要有一个返回值。
posted @ 2020-12-14 17:38  哆啦梦乐园  阅读(127)  评论(0编辑  收藏  举报