为什么如果没有处理,fmt.Print()会返回一个错误?

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

Why does fmt.Print() returns an error if no one handles it

问题

我经常被这个问题困扰,为什么 fmt.Print() 会返回一个错误?

我从来没有遇到过需要它的情况。

JavaPython 中,向 stdout 打印通常不会返回错误。
C# 中,向 stdout 打印可能会导致 OOMException。

理论上,这可能是内存溢出,但试图写入一些内容然后导致这种情况将是一个无法恢复的 panic,并且程序很可能会被终止。

或者也许这是为了让程序知道退出已经关闭?
如果不写入内容,你无法检测到管道中的进程是否已经终止,对吗?

有人曾经不得不处理过这个错误吗?

英文:

I am often tormented by the question, why does fmt.Print() return an error?

I have never met a situation where I needed it.

In Java and Python, printing to stdout usually does not returns an error.
In C#, printing to stdout can cause OOMException.

This, in theory, may be OOM, but there is no point in trying to write something then cause this will be an unrecoverable panic and the program most likely will be killed.

Or maybe this is necessary so that the program can understand that the exit is closed?
You can't detect if the process down the pipe has terminated without writing to it, right?

Has anyone ever had to handle this error?

答案1

得分: 3

将内容翻译为中文:

如果在打印输出时关闭了stdout,那么会返回一个错误。如果stdout被重定向到管道或文件中,这一点尤其重要。

大多数应用程序都会忽略这个错误。

英文:

Printing to stdout can return an error if, for instance, stdout is closed while printing. This is especially relevant if stdout is redirected to a pipe or to a file.

Most applications ignore this error though.

huangapple
  • 本文由 发表于 2021年11月19日 00:50:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/70023712.html
匿名

发表评论

匿名网友

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

确定