Search code examples
gosemantics

*strings.Reader leaving target buffer blank


I am attempting to pass an *strings.Reader from one function to another. The content of the reader is "Foo". This is the code that creates/passes the reader:

_, err = funcNum2(strings.NewReader("Foo"))

... and the code that reads from it...

buf := []byte{}
_, err := reader.Read(buf)
if err != nil {
    fmt.Printf("Error reading from reader: %v\n", err)
}

When I run the debugger and look at the value of reader in method2, I find that reader still contains "Foo". However, can you please help me understand why, when I try to read into buf, buf is empty?


Solution

  • when assigning buf:=[]byte{}, a byte slice of size 0 is assigned. In order to read from buffer you can take size of the reader's buffer, reader.Size(), create a byte slice of that size. Write to it.

    following code works

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func print_reader(read *strings.Reader) {
        buf := make([]byte, 4) //give read.Size() here
        n, err := read.Read(buf)
        fmt.Println(n, err, string(buf), read.Size())
    }
    
    func main() {
        rd := strings.NewReader("test")
        print_reader(rd)
    }