io.WriteString func WriteString(w Writer, s string) (n int, err error) 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.Pipe io.Pipe を利用しない例 一度書き込んだ内容をバッファしている func ExamplePipeNG() { print := func(r 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
io.Pipe io.Pipe を利用した例 内部バッファがなくなった golang.org/src/io/example_test.go (https://golang.org/src/io/example_test.go) より引用 func ExamplePipe() { 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
参考資料 io - The Go Programming Language (https://golang.org/pkg/io/) Golang でのstream の扱い方を学ぶ (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)
License サンプルコードには以下からの引用が含まれます。 - golang.org/src/io/io.go (https://golang.org/src/io/io.go) - golang.org/src/io/example_test.go (https://golang.org/src/io/example_test.go) code is licensed under a BSD license.