Middle · Go foundations
io.Reader: data and an error together
Should a read loop discard bytes when Read returns an error?
Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.
Reveal a strong answer
Read can return n>0 together with an error, including EOF. Process the n bytes before handling the error, or a final partial chunk may be lost. A short read alone is not necessarily EOF.
Use io.ReadFull when an exact fixed-size record is required and inspect its documented errors. Use streaming decoders for structured input, enforce limits and preserve incomplete-record behavior.
A buffer may be reused on the next call. Copy retained bytes or transfer ownership explicitly before handing them to an asynchronous consumer; otherwise the next read can overwrite data still being used.
Common trap
A loop that checks err first can silently drop the final bytes of a valid stream.
Try it
A reader returns n3 and io.EOF on the same call. What must the consumer do?
Worked solution
Consume the first3 bytes, then handle EOF as end of input. If a protocol required4 bytes, treat that as a truncated record according to the protocol. Test n>0+EOF explicitly with a custom reader.
Change the constraint
Why is io.Copy often safer than inventing an ad hoc copy loop?
How did you do?
Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.
Not marked. Progress stays on this browser, separate from course completion.
Primary references
Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.