http://play.golang.org/p/Opb7pRFyMf
// func (f *File) Read(b []byte) (n int, err error)
record, err := reader.Read()
Read()函数是否定义在os包中? 我试图理解这段代码,但找不到 Read() 函数的定义位置……如果那是 os 包中的那个,它会返回记录变量的整数。但是怎么能打印出文本文件中的文字呢?
最佳答案
Reader
是包装基本 Read
方法的接口(interface)。
type Reader interface {
Read(p []byte) (n int, err error)
}
Read
方法将 byte slice 段作为参数并返回 (读取的字节数,错误)
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])
将 slice arr
的内容转换为字符串。
要了解有关 Read
和 io.Reader
的更多信息,请参阅 article
关于io - 读取()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414427/