go 函數類型


在go中,函數也可以被當成數據類型

e.g:下面有兩個函數,+、-,然后定義了一個函數類型FuncType1,然后對funcType1附於不同的函數,則funcType1就可以執行相應的函數

package main

import (
   "fmt"
   _ "testinit"
)


func main() {
   a:=10
   b:=10
   var funcType1 FuncType1  = Add1
   fmt.Println(funcType1(a,b))
   funcType1 = Minus1
   fmt.Println(funcType1(a,b))
}

func init()  {
   fmt.Println("main init()")
}

func Add1(a,b int) int {
   return a+b
}

func Minus1(a,b int) int  {
   return a-b
}

//定義函數類型
type FuncType1 func(int,int) int

 這樣就是對funcType1附了兩次值,還可以進一步調整,如下

package main

import (
	"fmt"
	_ "testinit"
)


func main() {
	a:=10
	b:=10
	/*var funcType1 FuncType1  = Add1
	fmt.Println(funcType1(a,b))
	funcType1 = Minus1
	fmt.Println(funcType1(a,b))*/

	fmt.Println(Cal(a,b,Add1))

	fmt.Println(Cal(a,b,Minus1))
}

func init()  {
	fmt.Println("main init()")
}

func Add1(a,b int) int {
	return a+b
}

func Minus1(a,b int) int  {
	return a-b
}

type FuncType1 func(int,int) int

//定義函數,將函數類型當成一種函數參數 func Cal(a,b int,funcType FuncType1) (result int) { return funcType(a,b) }

  

定義一個新的函數,將函數類型當成一種函數參數,這樣就可以不用給函數類型附值,而直接用,方便了很多,也靈活了很多


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM