Golang:为什么 strings.Builder.WriteByte API 表示它可能返回一个错误?

huangapple go评论94阅读模式
英文:

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

问题

在函数实现的上方注释中(https://golang.org/src/strings/builder.go),我们可以看到:“返回的错误始终为nil。”对于所有其他写入字符串构建器的变体也是如此。

在内部,如果内部缓冲区已满且操作系统拒绝重新分配所需的内存,这些函数可能会失败,但显然在实现中没有处理这种情况。

使用此API的用户是否应该考虑在将来的标准库版本中Write*可能返回错误?如果不需要,为什么它可以返回错误?

英文:

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?

答案1

得分: 6

错误返回参数是为了满足特定的接口要求,比如io.ByteWriter。换句话说,虽然strings.BuilderWriteByte的实现可能不会失败,但是其他实现了相同方法并满足相同接口的实现可能会返回错误。

这在bytes.Buffer的文档中更明确地说明了。还可以参考bufio.Writer

为了更具未来性的程序实现,我建议您无论文档如何,都要继续检查错误。

英文:

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.

huangapple
  • 本文由 发表于 2021年10月17日 21:10:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/69604663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定