gpt4 book ai didi

types - 无开销的开关接口(interface)实现

转载 作者:IT王子 更新时间:2023-10-29 00:44:25 28 4
gpt4 key购买 nike

给定一个接口(interface)和两个(或更多)实现,我很难在扩展功能时轻松切换实现。

例如,假设有一个支持 Inc 和 String 的接口(interface) INumber 以及两个实现 NumberInt32 和 NumberInt64 及其明显的实现。假设我想在 INumber 之上实现一个 EvenCounter。 EvenCounter 只有一个 IncTwice 并且应该调用 Inc 两次。如果不在 EvenCounter 中的 INumber 周围使用额外的结构,我很难获得正确的类型。

type INumber interface {
Inc()
String() string
}

type NumberInt32 struct {
number int32
}

func NewNumberInt32() INumber {
ret := new(NumberInt32)
ret.number = 0
return ret
}

func (this *NumberInt32) Inc() {
this.number += 1
}

func (this *NumberInt32) String() string {
return fmt.Sprintf("%d", this.number)
}

// type NumberInt64.... // obvious

这是我奋斗的地方

type EvenCounter1 INumber // nope, additional methods not possible 
type EvenCounter2 NumberInt32 // nope
func (this *EvenCounter2) IncTwice() {
for i:=0; i < 2; i+=1 {
// this.Inc() // Inc not found
// INumber(*this).Inc() // cannot convert
// in, ok := *this.(INumber) // cannot convert
// v, ok := this.(INumber) // cannot convert
// a concrete conversion a) does not work and b) won't help
// here it should be generic
// v, ok := this.(NumberInt32)
// How do I call Inc here on this?
}
}

只需嵌入到一个结构中就可以了...

type EvenCounter3 struct {
n INumber
}

func (this *EvenCounter3) IncTwice() {
n := this.n // that is a step I want to avoid
n.Inc() // using this.n.Inc() twice makes it slower
n.Inc()
}

func (this *EvenCounter3) String() string {
return this.n.String()
}

我可以忍受为每个方法手动实现委托(delegate)的需要,但是显然我想依赖 INumber 而不是具体的实现(即将意味着改变很多地方来尝试另一种实现,但是,我想避免额外的间接访问和(很可能?)额外的空间。有没有避免结构并直接说 EvenCounter 是具有其他方法的(特定)INumber 的方法?

顺便说一下,真实的例子是一组整数和一个整数到整数的映射,其中有数百万个实例相互交织(不,仅仅 map[int]bool 是不够的——太慢了,bitset 很有趣,具体取决于用例等)并通过更改代码中的 2-3 行轻松测试集合和映射的不同实现(理想情况下只是类型,也许实例的通用创建。复制)

感谢任何帮助,我希望这还没有被问到......

最佳答案

您使用嵌入的变体实际上并未嵌入。 Embedded fields are anonymous and Go then delegates automatically .

这将您的示例简化为:

type EvenCounter3 struct {
INumber
}

func (this *EvenCounter3) IncTwice() {
this.Inc() // using this.n.Inc() twice makes it slower
this.Inc()
}

注意 String() 是自动委托(delegate)的(在 Go 语言中是“提升的”)。

至于调用 Inc() 两次使其变慢,好吧,这是使用接口(interface)的限制。接口(interface)的要点是不公开实现,因此您无法访问其内部数字变量。

关于types - 无开销的开关接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14869440/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com