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

huangapple go评论107阅读模式
英文:

What does this function initialization syntax mean?

问题

在查看Go语言中的google plus sign in时,我发现了一个非常有趣的模式。这里有一个简单的示例(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?我不明白!

谢谢。

英文:

While looking at the google plus sign in in go, I found a very interesting pattern. Here is a trivial example (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))
}

My question is quite simple, how come can we initiate the FuncType with parentheses? I do not understant!

Thanks.

答案1

得分: 4

Go规范:转换

> 转换是形式为 T(x) 的表达式,其中 T 是一个类型,x 是一个可以转换为类型 T 的表达式。

所以,

fn := FuncType(MultiplyByThree)

FuncType 是一个类型。而 MultiplyByThree 是一个指向函数的指针(也是一个表达式),具有与 FuncType 相同的签名。因此,它可以转换为这个类型。

顺便说一下,输出结果有点错误。应该是

> 返回 5 * 3 * 2: 30

这是正确的乘法顺序。 这个函数初始化语法是什么意思?

英文:

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.

So,

fn := FuncType(MultiplyByThree)

FuncType is a type. And MultiplyByThree is a pointer to function (which is an expression) with the same signature as FuncType. Therefore, it can be converted to this type.

BTW, the output is slightly wrong. Should be

> returns 5 * 3 * 2: 30

This is the correct sequence of multiplications. 这个函数初始化语法是什么意思?

huangapple
  • 本文由 发表于 2014年1月29日 03:46:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/21415334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定