Re:How to Use Go Interfaces
by ramenmeal on Monday March 19, 2018 @07:40PM
(#16624486)
Would this lead to the same or very similar interfaces being defined multiple times? Maybe that's not a problem?
[ Parent
| on HN ]
One of the more surprising things about Go is that you don't need to name interfaces at all. This:
func f1(r io.Reader) {}
Is the same as: func f2(r interface{ Read([]byte) (int, error) }) {}
In fact this is super common, with the empty interface: func f3(r interface{})
But somehow the ramifications of that don't sink in and we fail to generalize the principle.One practical usage:
li, _ := net.Listen("tcp", ":9000")
for {
conn, err := li.Accept()
if err != nil {
if err, ok := err.(interface {
Temporary() bool
}); ok && err.Temporary() {
time.Sleep(time.Second)
continue
} else {
panic(err)
}
}
}
This takes a bare interface and checks to see if it supports the "Temporary() bool" interface (which all net errors do). When paired with a type switch this makes for very interesting behavior: switch err := err.(type) {
case nil:
case interface{ Temporary() bool }:
if err.Temporary() {
time.Sleep(time.Second)
continue
}
panic(err)
default:
panic(err)
}
https://play.golang.org/p/J66vaIBGrs2All that to say, creating duplicate interfaces is perfectly fine.