Go语言入门到实战——09.Go语言里的函数

Go语言入门到实战——00主目录
在上一讲中我们学习了Go语言的string类型的使用和相关知识。

一.Go语言里的函数的特点

1.可以有多个返回值
2.所有的参数都是值传递:slice,map,channel可能会造成传引用错觉(这个没有必要纠结)
3.函数可以作为变量的值
4.函数可以作为参数和返回值

1.多返回值例子

package test

import (
	"math/rand"
	"testing"
)

func getMultiReturns() (int, int) {
    
    //指明返回值为两个int
	return rand.Intn(10), rand.Intn(20)
}

func TestFunc(t *testing.T) {
    
    
	t.Log(getMultiReturns())
}


2.作为参数和返回值以及变量

package test
import (
	"fmt"
	"testing"
	"time"
)
func timeSpent(inner func(op int) int) func(op int) int {
    
     //参数是函数,返回值也是函数
	return func(n int) int {
    
     //自定义函数并进行返回
		start := time.Now()
		ret := inner(n)//运行n秒
		fmt.Println("time spent is: ", time.Since(start).Seconds())//打印运行时间
		return ret //调用inner函数返回当前函数的值
	}
}

func inner(op int) int {
    
    
	time.Sleep((time.Second) * time.Duration(op))
	fmt.Println("I am inner,runtime is ", op)
	return op
}
func TestFunc(t *testing.T) {
    
    
	fun := timeSpent(inner)
	t.Log(fun(3))
}

二.可变长参数和延迟运行

1.可变长参数

package test

import (
	"testing"
)

func Sum(args ...int) int {
    
    
	res := 0
	for _, val := range args {
    
    
		res += val
	}
	return res
}
func TestFunc(t *testing.T) {
    
    
	t.Log(Sum(1, 2, 3, 4))
}


2.延迟执行函数defer

package test

import (
	"fmt"
	"testing"
)

func clear() {
    
    
	fmt.Println("Clear Resources")
}
func TestFunc(t *testing.T) {
    
    
	defer clear()    //在函数执行完返回前执行或者函数执行过程中报错
					 //也会执行完改defer函数再去退出
	t.Log("Started") //clear()由于是在最后执行,因此在"Started"之后
	panic("Err Fatal")
}

猜你喜欢

转载自blog.csdn.net/qq_44932835/article/details/121590891