object88
object88

Reputation: 760

Can a predeclared type implement an interface in Go?

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?

Upvotes: 0

Views: 111

Answers (1)

elithrar
elithrar

Reputation: 24260

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

Upvotes: 2

Related Questions