go - 这个函数初始化语法是什么意思?

标签 go

同时查看 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?我不明白!

谢谢。

最佳答案

Go spec: Conversions :

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/

相关文章:

go - 我可以在 Golang 中子类化并重新定义一个方法吗?

go - 如何在 gin 包中使用 golang 将 url 的某些部分作为子字符串?

node.js - 一个域上的多个应用程序

go - 无法导入包

go - 无法分配给 mapMeasures[ts].Delta

go - 构建接口(interface)

ajax - go - 如何获取请求消息正文内容?

go - 从名称中获取 reflect.Type

go - 将 rune 转换为int?

go - 我有一个在 Kubernetes 上运行的 Golang 应用程序,但是当 pod 死亡时根本没有错误消息。我应该怎么办?