Why does io.WriterTo's WriteTo method return an int64 rather than an int?

↘锁芯ラ 提交于 2020-05-14 18:33:12

问题


Most of the output methods in Go's io package return (int, error), for example io.Writer's Write([]byte) method and the io.WriteString(io.Writer, string) function. However, a few of the output methods, such as io.WriterTo's WriteTo method, return (int64, error) instead. This makes it inconvenient to implement WriteTo in terms of Write or WriteString without storing an intermediate value and type converting it from int to int64. What is the reason for this discrepancy?


回答1:


It's possible that WriteTo copies more than int32 bytes of data.

With the io.Readerand io.Writer interfaces, the amount of data is limited by the size of the given slice, which has a length limited by int for the current architecture.




回答2:


The signature of the Writer.Write() method:

Write(p []byte) (n int, err error)

It writes the contents of a slice. Quoting from the spec: Slice types:

A slice is a descriptor for a contiguous segment of an underlying array...

As we all know, the slice has an underlying array. Quoting again from the Spec: Array types:

The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int.

So the maximum length of an array is limited by the maximum value of the int type (which is 2147483647 in case of 32 bit and 9223372036854775807 in case of 64 bit architectures).

So back to the Writer.Write() method: since it writes the content of the passed slice, it is guaranteed that the number of written bytes will not be more that what fits into an int.

Now WriteTo.WriteTo() method:

WriteTo(w Writer) (n int64, err error)

A slice or array is nowhere mentioned. You have no guarantees that the result will fit into an int, so the int64 is more than justified.

Example: BigBuffer

Imagine a BigBuffer implementation which temporarily writes data into an array or slice. The implementation may manage multiple arrays so that if one is full (e.g. reached max int), continues in another one. Now if this BigBuffer implements the WriteTo interface and you call this method to write the content into an os.File, the result will be more than max int.



来源:https://stackoverflow.com/questions/29658892/why-does-io-writertos-writeto-method-return-an-int64-rather-than-an-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!