在Go语言中,预声明的类型可以实现接口。

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

Can a predeclared type implement an interface in Go?

问题

假设我有一个名为 Key 的接口,其中包含一个名为 Hash() int 的方法,我想在 Go 中的一个集合结构中使用它。我希望在我的集合中能够执行 (c *Collection) Set(key Key, value Value) 等操作。我希望我的集合能够以预声明类型作为键,例如 type IntKey int,这样我就可以在实现 (k IntKey) Hash() int 时利用一些有限的隐式类型转换。这种情况是否可行,还是我需要将 IntKey 声明为一个结构体?

英文:

Let's say that I have an interface, Key, which has a method Hash() int, that I would like to use in a collection struct in Go. I would like to be able to do things in my collection such as (c *Collection) Set(key Key, value Value). I would like my collection to be able to be keyed on predeclared types, such as type IntKey int, so that I can take advantage of some limited implicit typing while implementing (k IntKey) Hash() int. Is this possible, or to I need to declare IntKey as a struct?

答案1

得分: 2

任何(非内置)类型都可以满足一个接口,因此:

type IntKey int

func (k IntKey) Hash() int { ... }

和...

type Collection struct {
    // 字段
}

func (c Collection) Hash() int { ... }

两者都满足你的 Key 接口。更多阅读:https://golang.org/ref/spec#Interface_types

英文:

Any (non built-in) type can satisfy an interface, thus:

type IntKey int

func (k IntKey) Hash() int { ... }

and ...

type Collection struct {
    // fields
}

func (c Collection) Hash() int { ... }

Both satisfy your Key interface. Further reading: https://golang.org/ref/spec#Interface_types

huangapple
  • 本文由 发表于 2016年11月25日 03:35:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/40793502.html
匿名

发表评论

匿名网友

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

确定