Learning Functional Programming in Go
上QQ阅读APP看书,第一时间看更新

Interface embedding to add minor features

Here's another example of using interface embedding:

type BytesReadConn struct {
net.Conn
BytesRead uint64
}

func (brc *BytesReadConn) Read(p []byte) (int, error) {
n, err := brc.Conn.Read(p)
brc.BytesRead += uint64(n)
return n, err
}

By embedding  net.Conn in our BytesReadConn we are able to override its Read method not only perform the Conn.Read operation, but also to count the number of bytes read.

There's an ELO song that's ringing in my head now.