在 go 語言中,我們可以把函式作為一種變數,用 type 去定義它,那麼這個函式型別就可以作為值傳遞,甚至可以實現方法,這一特性是在太靈活了,有時候我們甚至可以利用這一特性進行型別轉換。作為值傳遞的條件是型別具有相同的引數以及相同的返回值。
go 語言的型別轉換基本格式如下:
type_name(expression)
複製**
舉個例子:
package main
import
"fmt"
type calculatetype func
(int, int) // 宣告了乙個函式型別
// 該函式型別實現了乙個方法
func
(c *calculatetype)
serve()
// 加法函式
func
add(a, b int)
// 乘法函式
func
mul(a, b int)
func
main()
// 5
// 6
// 我是乙個函式型別
// 我是乙個函式型別
複製**
如上,宣告了乙個 calculatetype 函式型別,並實現 serve() 方法,並將擁有相同引數的 add 和 mul 強制轉換成 calculatetype 函式型別,同時這兩個函式都擁有了 calculatetype 函式型別的 serve() 方法。
package main
import
"fmt"
type calculatetype func
(a, b int)
int // 宣告了乙個函式型別
// 加法函式
func
add(a, b int)
int
// 乘法函式
func
mul(a, b int)
int
func
calculate
(a, b int, f calculatetype)
int
func
main()
// 5
// 6
複製**
如上例子,calculate 的 f 引數型別為 calculatetype,add 和 mul 函式具有和 calculatetype 函式型別相同的引數和返回值,因此可以將 add 和 mul 函式作為引數傳入 calculate 函式中。
// handlefunc registers the handler function for the given pattern
// in the defaultservemux.
// the documentation for servemux explains how patterns are matched.
func
handlefunc
(pattern string, handler func(responsewriter, *request))
複製**
// handlefunc registers the handler function for the given pattern.
func
(mux *servemux)
handlefunc
(pattern string, handler func(responsewriter, *request))
複製**
type handlerfunc func
複製**
剛開始看到這段原始碼的時候,真的有點懵逼了,這段原始碼的目的是為了將我們的 handler 強制實現 servehttp() 方法,如下例子:
複製**因為 handlerfunc 是乙個函式型別,而 sayhi 函式擁有和 handlerfunc 函式型別一樣的引數值,因此可以將 sayhi 強制轉換成 handlerfunc,因此 sayhi 也擁有了 servehttp() 方法,也就實現了 handler 介面,同時,handlerfunc 的 servehttp 方法執行了它自己本身,也就是 sayhi 函式,這也就可以看出來了,sayhi 就是 handler 被呼叫之後的執行結果。
Golang 中函式作為值與型別
在 go 語言中,我們可以把函式作為一種變數,用 type 去定義它,那麼這個函式型別就可以作為值傳遞,甚至可以實現方法,這一特性是在太靈活了,有時候我們甚至可以利用這一特性進行型別轉換。作為值傳遞的條件是型別具有相同的引數以及相同的返回值。go 語言的型別轉換基本格式如下 type name ex...
GoLang 函式作為 型別 和 值
示例 package test import fmt testing type testint func int bool func isodd integer int bool return true func iseven integer int bool return false func f...
Go中函式作為值 型別傳遞。
在go中函式也是一種變數,我們可以通過type來定義它,它的型別就是所有擁有相同的引數,相同的返回值的一種型別 type typename func input1 inputtype1 input2 inputtype2 result1 resulttype1 函式作為型別到底有什麼好處呢?那就是可...