慕课网Go-3.函数、defer、panic、recover

函数

package main

import "fmt"

func add(a int, b int) (int, error) {
	return a + b, nil
}

func add2(a int, b int) (sum int, err error) {
	sum = a + b
	err = nil
	return sum, err
}

// 参数数量任意
func add3(items ...int) (sum int) {
	for _, value := range items {
		sum += value
	}
	return sum
}

//函数是一等公民,可以作为变量、参数

// 闭包:可以随时归零,而且不需要全局变量
func autoIncrement() func() int {
	local := 0
	return func() int {
		local += 1
		return local
	}
}

func main() {
	sum := add3(1, 2, 3)
	fmt.Println(sum)

	//闭包
	next := autoIncrement()
	for i := 0; i < 5; i++ {
		fmt.Print(next()) //1,2,3,4,5
	}
	fmt.Println()

	next2 := autoIncrement()
	for i := 0; i < 3; i++ {
		fmt.Print(next2()) //1,2,3
	}
}

defer

package main

import (
	"fmt"
	"sync"
)

func deferReturn() (ret int) {
	defer func() {
		ret++
	}()
	return 10
}

func main() {
	var mu sync.Mutex
	mu.Lock()
	defer mu.Unlock() //defer语句在return之前才执行

	//defer执行的顺序为栈的顺序,LIFO
	defer fmt.Println("1")
	defer fmt.Println("2")

	ret := deferReturn()
	fmt.Println(ret)//11,defer有能力改变返回值
}

panic、recover

package main

import "fmt"

func main() {

	defer func() {
		r := recover()
		if r != nil {
			fmt.Println("recover!!!")//捕获panic
		}
	}()

	panic("panic!!!") //直接导致程序退出
	fmt.Println("1")
}

你可能感兴趣的:(慕课网Go,golang,开发语言,后端)