为什么Go的bufio在内部使用panic?

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

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.wb.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.

huangapple
  • 本文由 发表于 2016年4月26日 13:10:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/36855714.html
匿名

发表评论

匿名网友

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

确定