typestar

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

  1. Anything that reads bytes satisfies Reader.
  2. io.Copy moves bytes between any pair of them.
  3. strings.NewReader and bytes.Buffer are the test doubles.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Standard interfaces, step 10 of 19 in Interfaces & generics.

← Previous Next →