io - 读取()函数

标签 io go

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 的内容转换为字符串。

要了解有关 Readio.Reader 的更多信息,请参阅 article

关于io - 读取()函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414427/

相关文章:

go - 从 100 x 100 QR 码创建二维位数组

java - 设计 ByteArrayOutputStream 公共(public)接口(interface)的理由?

python - 将 chr(13) 写入文件时读取时会给出 chr(10)

scala - io monad 的理解不打印任何内容

c - MPI I/O,单进程和多进程输出的混合

go - golang中的反引号 (`` ) 和双引号 ("") 有什么区别?

python - 在文本文件 Python 中写入时,将新行符号保留在字符串中

bash - 如何使用 bash -c 启动程序,重定向/禁用该应用程序的 GUI

go - 我正在使用 Antlr4 创建一种语言,然后我想用它生成 LLVM IR。我是否需要手写 LLVM IR 来响应我的访问者事件?

reflection - 是否可以在 go 中动态创建带有接收器(方法)的函数?