如何在Go语言中使用接口中的函数类型

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

How to use function types in interfaces in Go

问题

在函数类型IntStringFunc上调用方法SomeFunc的语法是:

var f IntStringFunc
f.SomeFunc(i, s)

其中,f是一个类型为IntStringFunc的变量,is是SomeFunc方法的参数。通过变量f调用SomeFunc方法,并传入参数is

英文:

I have the following code

type SomeInterface interface {
	SomeFunc(int, string)
}

type IntStringFunc func(int, string)

func (f IntStringFunc) SomeFunc(i int, s string) {
	f(i, s)
}

What is the syntax for invoking the method SomeFunc on the function type IntStringFunc?

答案1

得分: 1

方法调用语法不依赖于接收器类型,它始终是相同的:value.methodName(params)

例如:

var f IntStringFunc = func(i int, s string) {
    fmt.Printf("f(%d, %s)\n", i, s)
}

f.SomeFunc(1, "one")

这将输出(在Go Playground上尝试):

f(1, one)

由于f的类型是函数类型,你当然也可以像这样调用它:

f(1, "one")

这当然会打印相同的结果。

英文:

The method calling syntax does not depend on the receiver type, it's always the same: value.methodName(params).

For example:

var f IntStringFunc = func(i int, s string) {
	fmt.Printf("f(%d, %s)\n", i, s)
}

f.SomeFunc(1, "one")

This will output (try it on the Go Playground):

f(1, one)

Since type of f is a function type, you can of course call it too like this:

f(1, "one")

Which of course will print the same.

huangapple
  • 本文由 发表于 2022年3月12日 18:19:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/71448828.html
匿名

发表评论

匿名网友

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

确定