Use strings.Reader and bytes.Buffer
Use strings.Reader and bytes.Buffer
strings.Reader turns a string into a read-only seekable byte stream. Its cursor advances as you read. bytes.Buffer is a growable byte buffer supporting reads and writes. Both have usable zero values and help test I/O functions without files or network connections.
package main
import ( "fmt" "io" "strings")
func main() { r := strings.NewReader("hello") p := make([]byte, 2) n, err := io.ReadFull(r, p) fmt.Println(string(p[:n]), err == nil, r.Len(), r.Size()) r.Reset("go") fmt.Println(r.Len(), r.Size())}Len reports unread bytes; Size reports the original source length. Reset changes the source and resets the cursor. Reading UTF-8 by byte count may split a rune; use ReadRune when rune boundaries matter.
Expected output:
he true 3 52 2Copy a buffer snapshot
package main
import ( "bytes" "fmt")
func main() { var b bytes.Buffer b.WriteString("abc") snapshot := append([]byte(nil), b.Bytes()...) b.Bytes()[0] = 'X' fmt.Println(b.String(), string(snapshot)) p := make([]byte, 1) n, err := b.Read(p) fmt.Println(string(p[:n]), err == nil, b.String())}Bytes exposes an alias to unread bytes, valid only until the next modification. Copy it for a durable snapshot. Reading consumes bytes and reduces Len. Avoid copying a nonzero Buffer by value; use pointers. An unbounded buffer may consume large amounts of memory.
Expected output:
Xbc abcX true bcTry it locally
Write "abcd" into bytes.Buffer, read exactly two bytes with ReadFull, then print the bytes read, success, remaining text and length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
I/O contracts 08: Use strings.Reader and bytes.Buffer
Check the lesson objective before moving on.
After reading two bytes from strings.NewReader("abcd"), what are Len and Size?
How can you retain Buffer.Bytes across subsequent writes?