Write with io.Writer and detect short writes
Write with io.Writer and detect short writes
An io.Writer accepts bytes through Write(p []byte) (n int, err error). A conforming writer returns a non-nil error whenever n is less than len(p). Partial writes may still change the destination. Check both the count and error; never assume an unsuccessful write left the destination untouched.
package main
import ( "bytes" "fmt" "io")
func main() { var b bytes.Buffer var w io.Writer = &b n, err := w.Write([]byte("go")) fmt.Println(n, err == nil, b.String())}bytes.Buffer implements io.Writer through its pointer. The count is bytes, not runes. The caller may reuse the input after Write returns because writers must not retain or modify p.
Expected output:
2 true goDetect a broken writer
package main
import ( "fmt" "io")
type short struct{}
func (short) Write(p []byte) (int, error) { if len(p) == 0 { return 0, nil } return len(p) - 1, nil}func checked(w io.Writer, p []byte) error { n, err := w.Write(p) if err != nil { return err } if n != len(p) { return io.ErrShortWrite } return nil}func main() { fmt.Println(checked(short{}, []byte("abc")) == io.ErrShortWrite) fmt.Println(checked(io.Discard, []byte("abc")) == nil)}short intentionally violates the Writer contract. The checked function converts a short nil-error result into ErrShortWrite. io.Discard accepts bytes without retaining them. Retrying an entire message after a partial write may duplicate data; recovery depends on the destination protocol.
Expected output:
truetrueTry it locally
Write the string "report" to a bytes.Buffer using io.WriteString. Print the byte count, whether the error is nil, and the saved text.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
I/O contracts 02: Write with io.Writer and detect short writes
Check the lesson objective before moving on.
What must a conforming Writer return on a short write?
Why can retrying the whole buffer after a partial write be incorrect?