是否可以在Go中定义匿名接口实现? [英] Is it possible to define an anonymous interface implementation in Go?

查看:45
本文介绍了是否可以在Go中定义匿名接口实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一些给定的接口以及像这样使用它的假想库的功能

Consider some given interface and a function of an imaginary library that uses it like

// Binary and Ternary operation on ints
type NumOp interface {
    Binary(int, int) int
    Ternary(int, int, int) int
}

func RandomNumOp(op NumOp) {
    var (
        a = rand.Intn(100) - 50
        b = rand.Intn(100) - 50
        c = rand.Intn(100) - 50
    )
    fmt.Printf("%d <op> %d = %d\n", a, b, op.Binary(a,b))
    fmt.Printf("%d <op> %d <op> %d = %d\n", a, b, c, op.Ternary(a,b,c))
}

实现该接口的可能类型可能是

A possible type implementing that interface could be

// MyAdd defines additions on 2 or 3 int variables
type MyAdd struct {}
func (MyAdd) Binary(a, b int) int {return a + b }
func (MyAdd) Ternary(a, b, c int) int {return a + b + c }

我正在处理许多不同的接口,这些接口定义了一些函数,在某些情况下,需要使用大多数像 NOP 一样的函数来实现这些函数,而不依赖于任何结构 member ,并且仅在项目中的单个位置使用(无需重复使用).

I am dealing with many different interfaces defining a few functions that in some cases need to be implemented using functions mostly working as NOP-like operations, do not rely on any struct member and are only used in a single position in the project (no reusability needed).

Go中是否有一种更简单(较不冗长)的方法来定义使用匿名函数的(最好是)匿名接口的实现,就像(伪代码,我知道那样行不通):

Is there a simpler (less verbose) way in Go to define a (preferably) anonymous implementation of an interface using anonymous functions, just like (pseudo code, I know it's not working that way):

RandomNumOp({
   Binary: func(a,b int) int { return a+b},
   Ternary: func(a,b,c int) int {return a+b+c},
})

推荐答案

如果实施必须可行

如果实现该接口的值必须有效(例如,其方法必须可以调用而不会出现紧急情况),那么您将无法做到这一点.

If implementation must work

If the value implementing the interface must work (e.g. its methods must be callable without panic), then you can't do it.

方法声明必须在顶层(文件级).并且要实现一个具有0个以上方法的接口,则需要在某处放置方法声明.

Method declarations must be at the top level (file level). And to implement an interface that has more than 0 methods, that requires to have the method declarations somewhere.

当然,您可以使用结构并嵌入现有的实现,但是再次,它需要已经有一个现有的实现,其方法必须已经在文件级某处"定义.

Sure, you can use a struct and embed an existing implementation, but then again, it requires to already have an existing implementation, whose methods must already be defined "somewhere": at the file level.

如果您需要虚拟"但可行的实现,则可以使用/传递 any 实现,例如您的 MyAdd 类型的值.如果您想强调实现无关紧要,请创建一个虚拟实现,其名称表示:

If you need a "dummy" but workable implementation, them use / pass any implementation, e.g. a value of your MyAdd type. If you want to stress that the implementation doesn't matter, then create a dummy implementation whose name indicates that:

type DummyOp struct{}

func (DummyOp) Binary(_, _ int) int     { return 0 }
func (DummyOp) Ternary(_, _, _ int) int { return 0 }

如果您需要动态提供方法的 some 的实现,则可以创建一个代表该方法功能的委托结构类型,然后实际方法检查是否已设置相应的功能.称为哪种情况,否则将无济于事.

If you need to supply implementation for some of the methods dynamically, you may create a delegator struct type which holds functions for the methods, and the actual methods check if the respective function is set, in which case it is called, else nothing will be done.

它是这样的:

type CustomOp struct {
    binary  func(int, int) int
    ternary func(int, int, int) int
}

func (cop CustomOp) Binary(a, b int) int {
    if cop.binary != nil {
        return cop.binary(a, b)
    }
    return 0
}

func (cop CustomOp) Ternary(a, b, c int) int {
    if cop.ternary != nil {
        return cop.ternary(a, b, c)
    }
    return 0
}

使用它时,您可以自由地仅提供一部分功能,其余功能将为空:

When using it, you have the freedom to only supply a subset of functions, the rest will be a no-op:

RandomNumOp(CustomOp{
    binary: func(a, b int) int { return a + b },
})

如果不需要执行工作

如果您只需要一个实现接口的值,而又不需要其方法是可调用的"(调用时就不会慌张),则可以简单地使用一个匿名结构文字,嵌入接口类型:

var op NumOp = struct{ NumOp }{}

这篇关于是否可以在Go中定义匿名接口实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆