5 ms·
Would this lead to the same or very similar interfaces being defined multiple times? Maybe that's not a problem?
by ramenmeal 9y ago
Would this lead to the same or very similar interfaces being defined multiple times? Maybe that's not a problem?
- cdoxsey 9y agoOne 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/J66vaIBGrs2 https://play.golang.org/p/J66vaIBGrs2 All that to say, creating duplicate interfaces is perfectly fine.
- chewxy 9y agoShould probably name them - makes it readable. But you are correct - duplicate interfaces are fine