io.Reader and io.Writer in Go
The two interfaces that let unrelated things be plumbed together.
func pipe(text string) (string, int64, error) {
source := strings.NewReader(text)
var sink strings.Builder
written, err := io.Copy(&sink, source)
if err != nil {
return "", 0, fmt.Errorf("copy: %w", err)
}
return sink.String(), written, nil
}
func countingReader(text string) (int, error) {
reader := io.LimitReader(strings.NewReader(text), 8)
data, err := io.ReadAll(reader)
return len(data), err
}
How it works
- Anything that reads bytes satisfies Reader.
io.Copymoves bytes between any pair of them.strings.NewReaderandbytes.Bufferare the test doubles.
Keywords and builtins used here
errorfuncifintint64lenreturnstringvar
The run, in numbers
- Lines
- 16
- Characters to type
- 401
- Tokens
- 115
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 66 seconds.
Step 1 of 3 in Standard interfaces, step 10 of 19 in Interfaces & generics.