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

Time:12-17

source code below:

// 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
}

How about removing the nil error:

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

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related