Home > Mobile >  Golang: Why does strings.Builder.WriteByte API suggests it can return an error?
Golang: Why does strings.Builder.WriteByte API suggests it can return an error?

Time:10-18

In a comment above the function implementation (https://golang.org/src/strings/builder.go) we see: "The returned error is always nil.". The same applies to all other variants which write to the string builder.

Internally such functions can fail if the internal buffer is full and the OS denies memory required for reallocation, but clearly this is not handled in the implementation.

Should users of this API consider the possibility of Write* returning errors in future versions of the standard library? If not, why it can return an error?

CodePudding user response:

The error return parameter is there to satisfy a specific interface, like io.ByteWriter. In other words, while it's true that the strings.Builder implementation of WriteByte may not fail, other implementations of that same method, that also satisfy the same interface, may return an error.

This is stated more explicitly in the documentation of bytes.Buffer. See also bufio.Writer.

For a more future-proof implementation of your program I'd recommend that you keep checking the error regardless of what the documentation says.

  •  Tags:  
  • go
  • Related