同时查看 google plus sign in在go中,我发现了一个非常有趣的模式。这是一个简单的例子 ( live )。
package main
import(
"fmt"
)
type FuncType func(i int) int
func (fn FuncType) MultiplyByTwo(i int) int{
return fn(i) * 2
}
func MultiplyByThree(i int) int{
return i * 3
}
func main(){
fn := FuncType(MultiplyByThree)
fmt.Println("returns 2 * 3 * 5: ",fn.MultiplyByTwo(5))
}
我的问题很简单,为什么我们可以用括号启动 FuncType?我不明白!
谢谢。
最佳答案
Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.
所以,
fn := FuncType(MultiplyByThree)
FuncType
是一种类型。 MultiplyByThree
是一个指向函数(它是一个表达式)的指针,与 FuncType
具有相同的签名。因此,可以转换为该类型。
顺便说一句,输出有点错误。应该是
returns 5 * 3 * 2: 30
这是正确的乘法顺序。 :)
关于go - 这个函数初始化语法是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21415334/