英文:
Why Go's bufio uses panic under the hood?
问题
从bufio
包中阅读代码,我发现了以下内容:
// fill reads a new chunk into the buffer.
func (b *Reader) fill() {
...
if b.w >= len(b.buf) {
panic("bufio: tried to fill full buffer")
}
...
}
同时,Effective Go关于panic
的部分包含了以下段落:
这只是一个示例,但是真正的库函数应该避免使用panic。
如果问题可以被掩盖或解决,最好让程序继续运行,而不是导致整个程序崩溃。
所以,我想知道,标准库代码中的panic
调用是否因为特定的缓冲读取器出现了问题而变得如此重要?
英文:
Reading the code from the bufio
package I've found such things:
// fill reads a new chunk into the buffer.
func (b *Reader) fill() {
...
if b.w >= len(b.buf) {
panic("bufio: tried to fill full buffer")
}
...
}
At the same time the Effective Go section about panic
contains the next paragraph:
> This is only an example but real library functions should avoid panic.
> If the problem can be masked or worked around, it's always better to
> let things continue to run rather than taking down the whole program.
So, I wonder, is the problem with a particular buffered reader so important to cause the panic
call in the standard library code?
答案1
得分: 5
这可能是值得怀疑的,但请考虑:fill
是一个私有方法,b.w
和 b.buf
是私有字段。如果导致 panic 的条件确实为真,那么这是 bufio 实现中的逻辑错误。由于在首次进入该状态之前实际上不应该有可能进入该状态(一种“不可能发生”的情况),我们并不真正知道如何进入该状态,也不清楚在问题被检测到之前有多少其他状态被破坏,以及用户能否做些什么。在这种情况下,引发 panic 似乎是合理的。
英文:
It may be questionable, but consider: fill
is a private method, and b.w
and b.buf
are private fields. If the condition that causes the panic is ever true, it's due to a logic error in the implementation of bufio. Since it should never really be possible to get into that state in the first place (a "can't happen" condition), we don't really know how we got there, and it's unclear how much other state got corrupted before the problem was detected and what, if anything, the user can do about it. In that kind of situation, a panic seems reasonable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论