io.Writer に string を書き込んでくれる関数 自作 struct であっても、WriteString メソッドを生やしておこう。そうすると、 io.WriteString を使う時、 string から []byte への変換が走らず、効率がよい // WriteString writes the contents of the string s to w, which accepts a slice of bytes. // If w implements a WriteString method, it is invoked directly. // Otherwise, w.Write is called exactly once. func WriteString(w Writer, s string) (n int, err error) { if sw, ok := w.(stringWriter); ok { return sw.WriteString(s) } return w.Write([]byte(s)) }
io.Reader) { buf := new(bytes.Buffer) buf.ReadFrom(r) fmt.Print(buf.String()) } b := new(bytes.Buffer) // ← 不要なアロケート!! fmt.Fprint(b, "some text to be read\n") print(b) // Output: // some text to be read } Run
r, w := io.Pipe() go func() { fmt.Fprint(w, "some text to be read\n") w.Close() }() buf := new(bytes.Buffer) buf.ReadFrom(r) fmt.Print(buf.String()) // Output: // some text to be read } Run
func ExampleCopy() { r := strings.NewReader("some io.Reader stream to be read\n") if _, err := io.Copy(os.Stdout, r); err != nil { log.Fatal(err) } // Output: // some io.Reader stream to be read } Run
の扱い方を学ぶ (http://christina04.hatenablog.com/entry/2017/01/06/190000) Streaming IO in Go (https://medium.com/learning-the-go-programming-language/streaming-io-in-go-d93507931185) メルカリ カウルのマスタデータの更新 (https://www.slideshare.net/takuyaueda967/ss-82030886)