英文:
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.Builder
中WriteByte
的实现可能不会失败,但是其他实现了相同方法并满足相同接口的实现可能会返回错误。
这在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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论