Why a nil error returned from strings.Builder WriteString in golang, is it necessary?

Viewed 318

When reviewed my colleague's code, I found that a returned err has been ignored, though we would not do that in general:

b := new(strings.Builder)
b.WriteString("Hello, World!") // ignore err

The source code for WriteString declares it may return an error, but in fact it never will (always returning nil for the error value):

// WriteString appends the contents of s to b's buffer.
// It returns the length of s and a nil error.
func (b *Builder) WriteString(s string) (int, error) {
    b.copyCheck()
    b.buf = append(b.buf, s...)
    return len(s), nil
}

What would the issues be, if any, with removing the error return, as follows?

func (b *Builder) WriteString(s string) int {
    b.copyCheck()
    b.buf = append(b.buf, s...)
    return len(s)
}
2 Answers

The changelist which introduces strings.Builder includes a lot of comments about trying to make this API similar to bytes.Buffer.

For instance,

That's how a bytes.Buffer behaves, after all, and we're supposed to be a subset of a bytes.Buffer.

Looking at the documentation for some bytes.Buffer functions, it mentions

WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer, returning its length and an error, which is always nil but is included to match bufio.Writer's WriteRune.

It looks like they're basically trying to design an API that's similar to other interfaces in Golang's standard library. Even though the always-nil error is redundant, it allows the Builder to match existing interfaces that would accept bytes.Buffer or bufio.Writer. One such interface is io.StringWriter, which looks like

type StringWriter interface {
    WriteString(s string) (n int, err error)
}

The err return value here is useful since other StringWriter implementations could possibly return errors.

Go, it's quite common to return a value and error. So you can check the error is not null, if no error then easily use the returned value. In other words, if it receives an error from a function then it indicates there was a problem with the function called.

Related