英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论