July 2019
Intermediate to advanced
458 pages
12h 12m
English
Any Go application can define a custom implementation of the io.Reader interface. A good general rule when implementing interfaces is to accept interfaces and return concrete types, avoiding unnecessary abstraction.
Let's look at a practical example. We want to implement a custom reader that takes the content from another reader and transforms it into uppercase; we could call this AngryReader, for instance:
func NewAngryReader(r io.Reader) *AngryReader { return &AngryReader{r: r}}type AngryReader struct { r io.Reader}func (a *AngryReader) Read(b []byte) (int, error) { n, err := a.r.Read(b) for r, i, w := rune(0), 0, 0; i < n; i += w { // read a rune r, w = utf8.DecodeRune(b[i:]) // skip if not a letter if !unicode.IsLetter(r) ...Read now
Unlock full access