What "number of bytes written" should my io.Writer return when it intentionally does not write all the bytes it is passed

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

What "number of bytes written" should my io.Writer return when it intentionally does not write all the bytes it is passed

问题

我想创建一个实现io.Writer接口的结构体,即Write(p []byte) (n int, err error)。该结构体将忽略传递给它的某些字节,因此实际上不会写入p参数中的所有字节。(实际目的并不重要,但可以例如忽略前10个写入的字节,忽略每隔一个字节,或者其他改变调用者传递给该方法的字节数的操作)。

io.WriterWrite方法的文档中如下所述(重点在于我标注的部分):

> Write将p中的len(p)字节写入底层数据流。它返回从p中写入的字节数(0 ≤ n ≤ len(p))和导致写入提前停止的任何错误。如果返回的n < len(p),Write必须返回非nil的错误。Write不能修改切片数据,即使是临时修改。

作为n值,我应该返回什么?为了符合文档要求,成功时应返回len(p)。然而,该方法实际上可能没有写入那么多字节,返回值将是“错误”的。

英文:

I want to create a struct that implements io.Writer, ie Write(p []byte) (n int, err error). The struct will omit certain bytes that is passed to it and thus not actually write all the bytes that is passed in the p parameter. (The actual purpose isn't important, but it could for example be to ignore the first 10 bytes written, ignore every second byte or something else that alters the number of bytes written from what the caller passed to the method).

The documentation for io.Writer's Write method says the following (emphasis mine):

> Write writes len(p) bytes from p to the underlying data stream. It
> returns the number of bytes written from p (0 <= n <= len(p)) and any
> error encountered that caused the write to stop early. Write must
> return a non-nil error if it returns n < len(p)
. Write must not modify
> the slice data, even temporarily.

What should I return as the n value? To comply with the documentation, on success I should return len(p). However, the method might actually not have written that many bytes, and the return value will be "wrong".

答案1

得分: 4

成功时,返回 p 的长度。

当你写入 /dev/null 时调用的函数返回你尝试“写入”的字节数。它实际上并不写入任何内容,但它能正确地处理发送给它的数据。

我会假设在你的情况下,只有在你的写入程序无法正确处理所有发送给它的字节时,才会返回 n < len(p)。

然后,你的写入程序的文档应该非常清楚地说明哪些数据被写入和未被写入。使用你的函数的人需要知道在写入完成后可以检索到哪些数据。

英文:

On success, return len(p).

The function called when you write to /dev/null returns the number of bytes that you tried to "write" to it. It never actually writes anything, but it properly handles data being sent to it.

I would assume that in your case, you should only return n < len(p) if your writer was unable to properly handle all of the bytes sent to it.

Then, the documentation for your writer should very clearly state what data is and is not written. People using your function need to know what data will be retrievable after the write is finished.

huangapple
  • 本文由 发表于 2015年9月15日 02:26:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/32571504.html
匿名

发表评论

匿名网友

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

确定