ひとくちメモシリーズ
n, err := io.Copy(io.Discard, reader) がよさそう
discard は ReadFrom() を実装していて、何もしないで n だけとる
https://cs.opensource.google/go/go/+/refs/tags/go1.24.5:src/io/io.go;l=662-676
func (discard) ReadFrom(r Reader) (n int64, err error) { bufp := blackHolePool.Get().(*[]byte) readSize := 0 for { readSize, err = r.Read(*bufp) n += int64(readSize) if err != nil { blackHolePool.Put(bufp) if err == EOF { return n, nil } return } } }
io.Copy() は dst が io.ReadFrom() を実装してると buf の alloc なしでそれを使う
https://cs.opensource.google/go/go/+/refs/tags/go1.24.5:src/io/io.go;l=413-416
// copyBuffer is the actual implementation of Copy and CopyBuffer. // if buf is nil, one is allocated. func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) { // If the reader has a WriteTo method, use it to do the copy. // Avoids an allocation and a copy. if wt, ok := src.(WriterTo); ok { return wt.WriteTo(dst) } // Similarly, if the writer has a ReadFrom method, use it to do the copy. if rf, ok := dst.(ReaderFrom); ok { return rf.ReadFrom(src) } ...
ので、 n, err := io.Copy(io.Discard, reader) で負担少なくいい感じに n を取得できて happy という趣