0

http://play.golang.org/p/Opb7pRFyMf

    // func (f *File) Read(b []byte) (n int, err error)
    record, err := reader.Read()

Is the Read() function defined in os package? I am trying to understand this code but cannot find where the Read() function is defined... if that is the one in os package, it returns integer for record variable. But how come it is able to print out the text in the text file?

4

1 回答 1

0

Reader是包装基本Read方法的接口。

type Reader interface {
    Read(p []byte) (n int, err error)
}

Read方法将字节切片作为参数并返回(number of bytes read, error)

myReader := strings.NewReader("This is my reader")
arr := make([]byte, 4)
for {
// n is number of bytes read
    n, err := myReader.Read(arr)
    if err == io.EOF {
        break
    }
    fmt.Println(string(arr[:n]))
}

输出:

This
 is 
my r
eade
r

string(arr[:n])将切片的内容转换arr为字符串。

要了解有关Readand的更多信息io.Reader,请参阅本文

于 2018-10-22T11:29:55.450 回答