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

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

How to use function types in interfaces in Go

问题

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

  1. var f IntStringFunc
  2. f.SomeFunc(i, s)

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

英文:

I have the following code

  1. type SomeInterface interface {
  2. SomeFunc(int, string)
  3. }
  4. type IntStringFunc func(int, string)
  5. func (f IntStringFunc) SomeFunc(i int, s string) {
  6. f(i, s)
  7. }

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

答案1

得分: 1

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

例如:

  1. var f IntStringFunc = func(i int, s string) {
  2. fmt.Printf("f(%d, %s)\n", i, s)
  3. }
  4. f.SomeFunc(1, "one")

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

  1. f(1, one)

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

  1. f(1, "one")

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

英文:

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

For example:

  1. var f IntStringFunc = func(i int, s string) {
  2. fmt.Printf("f(%d, %s)\n", i, s)
  3. }
  4. f.SomeFunc(1, "one")

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

  1. f(1, one)

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

  1. 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:

确定