Golang函数变量——把函数作为值保存到变量中

1、概述

在Golang语言中,函数也是一种数据类型,可以赋值给一个变量,则该变量就是一个函数类型的变量了。通过该变量可以对函数调用。

2、Go语言函数变量详解

定义

func fun() {   
}
var f func()
f = fun

说明

我们首先定义了一个 fun 的函数,接着我们声明了一个类型是 func 的函数变量 f,并且将 fun 函数赋值给变量 f。

3、Go语言带参数的函数变量详解

定义

func fun(int)string {   
}
var f func(int) string
f = fun

说明

我们首先定义了一个 fun 的函数,函数的参数为一个 int 类型 的参数, 函数的返回值为一个 string 类型的值,接着我们声明了同样类型的函数变量 f,并且将 fun 函数赋值给变量 f。

4、函数变量示例 

示例一:

package main
import "fmt"
//定义一个函数:
func test(num int){
        fmt.Println(num)
}
func main(){
        //函数也是一种数据类型,可以赋值给一个变量	
        a := test//变量就是一个函数类型的变量
        fmt.Printf("a的类型是:%T,test函数的类型是:%T \n",a,test)//a的类型是:func(int),test函数的类型是:func(int)
        //通过该变量可以对函数调用
        a(10) //等价于  test(10)
}

输出:

a的类型是:func(int),test函数的类型是:func(int) 
10

示例二:

函数既然是一种数据类型,因此在Go中,函数可以作为形参,并且调用(把函数本身当做一种数据类型)。

package main
import "fmt"
//定义一个函数:
func test(num int){
	fmt.Println(num)
}
//定义一个函数,把另一个函数作为形参:
func test02 (num1 int ,num2 float32, testFunc func(int)){
	fmt.Println("-----test02")
	testFunc(num1)
}
func main(){
	//函数也是一种数据类型,可以赋值给一个变量
	a := test//变量就是一个函数类型的变量
	fmt.Printf("a的类型是:%T,test函数的类型是:%T \n",a,test)//a的类型是:func(int),test函数的类型是:func(int)
	//通过该变量可以对函数调用
	a(10) //等价于  test(10)
	//调用test02函数:
	test02(20,3.19,test)
	test02(30,3.19,a)
}

输出:

a的类型是:func(int),test函数的类型是:func(int) 
10
-----test02
20
-----test02
30

5、总结

在 Go 语言中,函数也是一种类型,可以和其他数据类型一样保存在变量中。Go 语言函数变量语法:

func fun() {   
}
var f func()
f = fun

Go 语言带参数的函数变量定义:

func fun(int)string {   
}
var f func(int) string
f = fun

将函数赋值给函数变量和函数调用的区别是将函数赋值给函数变量的时候是不带()的。

posted @ 2022-02-12 19:29  人艰不拆_zmc  阅读(1201)  评论(0编辑  收藏  举报