io.Writer
- Go course
- Intermediate
- Lesson 36/80
- 4 min
Learn the Writer interface and the Write method.
io.Writer
io.Writer is the counterpart of Reader:
type Writer interface {
Write(p []byte) (n int, err error)
}os.Stdout, files, bytes.Buffer, http.ResponseWriter, hashes and compressors are Writers. fmt.Fprintf(w, ...) writes formatted output to any Writer, so the same function can produce output to the screen, a file or an HTTP response.
io.MultiWriter and short writes
io.MultiWriter(a, b) duplicates every write to several targets (e.g. both the screen and a log file). By contract, Write must return an error if it didn't write all bytes, so checking only err is usually enough.
f, _ := os.Create("log.txt")
w := io.MultiWriter(os.Stdout, f)
fmt.Fprintln(w, "başladı") // written to bothPractice Testable output
Write rapor(w io.Writer, adlar []string); it writes each name as "- " + name on its own line. Call it on a bytes.Buffer and print buf.String() with fmt.Print.
Starter code
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"bytes"
"fmt"
"io"
)
func rapor(w io.Writer, adlar []string) {
for _, ad := range adlar {
fmt.Fprintln(w, "- "+ad)
}
}
func main() {
var buf bytes.Buffer
rapor(&buf, []string{"Ada", "Can"})
fmt.Print(buf.String())
}Expected output
- Ada - Can
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which signature best makes a report function testable?
- func rapor(dosya string)
- func rapor(w io.Writer, v Veri) error Correct answer
- func rapor(v Veri) // writes to os.Stdout
- func rapor() string
Explanation: A function taking a Writer can be called with a bytes.Buffer in tests and its output checked; in production os.Stdout or a file is passed.
2 Write to a Writer
func selam(w io.Writer, ad string) {
fmt.____(w, "Merhaba %s\n", ad)
}
func selam(w io.Writer, ad string) {
fmt.Fprintf(w, "Merhaba %s\n", ad)
}
Explanation: Fprintf writes formatted text to the given io.Writer.
3 Writer target
| Term | Meaning |
|---|---|
os.Stdout |
Screen |
bytes.Buffer |
Memory (tests) |
http.ResponseWriter |
HTTP response |
io.MultiWriter |
Multiple targets |