实现Reader界面 [英] Implementing Reader interface

查看:107
本文介绍了实现Reader界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解Go的接口的一般概念。不过,我最近正在考虑实现 io.Reader 界面,这让我感到困惑。我发现这篇文章没有什么帮助。



首先,接受的答案是使用 io.Reader 读取函数,据我所知,函数从未实现过。其次, Read 函数如何在类似于 ioutil.ReadAll 的上下文中工作。它需要实现 io.Reader 接口并返回一部分字节。我不明白如何将仅返回 int err 的东西处理成一段字节。



编辑:



我在IRC频道中获得了帮助,这是所提供的答案。你如何实际实现一个 http://play.golang.org/p/ejpUVOx8jR 。非常感谢go社区。

编辑2:



正如下面的实现所指出的那样,将会失败条纹大于缓冲区的情况。这是一个更加理智的实现 http://play.golang.org/p/t4Zg8TnF33

解决方案

您传递 Read 字节片。 Read 应该在其中放入字节。由于切片只是对数组的引用,因此更改切片内容会更改基础数组,因此 Read 的调用者可以检查它传递给它的切片。 / p>

ioutil.ReadAll 创建一个缓冲区并调用 ReadFrom on它。 ReadFrom 重复读取读取,增加缓冲区的大小,直到读取通过返回 io.EOF 作为错误告诉它已经用尽了。 亲自查看



您的答案链接确实实现了 io.Reader 界面。它声明了一个方法 Read(p [] byte)(n int,e error)。这就是所需要的。


I understand the general concept of Go's interfaces. However, I was recently looking into implementing the io.Reader interface, and it has me confused. I found this post which didn't help to much.

Reader interface and the Read method in golang

To start with, the accepted answer is using io.Reader's Read function, which as far as I can tell is never implemented. Second, how does the Read function work in the context of something like ioutil.ReadAll. It takes something that implemented the io.Reader interface and returns a slice of bytes. I don't understand how something that is returning only an int and err can be processed into a slice of bytes.

Edit:

I was helped in the go-nuts IRC channel and this was the provided answer as to how you would likely actually implement one http://play.golang.org/p/ejpUVOx8jR. Much thanks to the go community.

Edit 2:

as pointed out below the implementation above will fail in the case where the strign is larger than the buffer. This is a more sane implementation http://play.golang.org/p/t4Zg8TnF33.

解决方案

You pass Read the byte slice. Read is supposed to put bytes in it. As slices are just references to arrays, changing the contents of a slice changes the underlying array, so the caller of Read can then just check the slice it has passed to it.

ioutil.ReadAll creates a buffer and calls ReadFrom on it. ReadFrom calls Read repeatedly, increasing the size of the buffer until Read tells it has been exhausted by returning io.EOF as error. See for yourself.

The answer you link does implement the io.Reader interface. It is declaring a method Read(p []byte) (n int, e error). That's all what is needed.

这篇关于实现Reader界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆