Reader接口和golang中的Read方法 [英] Reader interface and the Read method in golang

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

问题描述

我正在关注golang之旅,并被要求:


实现一个实现io.Reader的rot13Reader并从io.Reader,通过将ROT13替换密码应用于所有字母字符来修改流。


我首先将方法应用于* rot13Reader

  type rot13Reader struct {
r io.Reader
}

func( r * rot13Reader)Read(p [] byte)(n int,e error){


}

然而,我无法理解这种Read方法。

p 是否包含所有读取的字节?因此,我应该做的就是遍历它们并应用ROT13替换?

据我所知,它应该返回读取的字节数和文件末尾的EOF错误,但我不确定何时以及如何调用此方法。所以回到我原来的问题中, p 是否包含所有读取的数据?如果不是,那我该怎么办呢? 字节(由 io.Reader rot13Reader 中读取的字节)。
$ b $ pre $ func(r * rot13Reader)Read(p [] byte)(n int,e error){
n, e = rrRead(p)
for i:= range(p [:n]){
p [i] = rot13(p [i])
}
return

rot13Reader 阅读器并在所述封装的Reader上调用 Read

它返回rot13的内容和读取的字节数。


I was following the golang tour and I have been asked to:

Implement a rot13Reader that implements io.Reader and reads from an io.Reader, modifying the stream by applying the ROT13 substitution cipher to all alphabetical characters.

I first implemented the method to the *rot13Reader

   type rot13Reader struct {
    r io.Reader
}

func (r *rot13Reader) Read(p []byte) (n int, e error){


}

However I can't get my head around this Read method.

Does the p contain all of the bytes read? And hence all I should do is iterate over them and apply the ROT13 substitution ?

I understand that it should return the number of bytes read and an EOF error at the end of the file however I'm not sure when and how this method is called. So coming back to my original question does the p contain all of the data read ? If not then how can I get to it?

解决方案

You should scan and "rot13" only n bytes (the one read by the io.Reader within rot13Reader).

func (r *rot13Reader) Read(p []byte) (n int, e error){
    n, e = r.r.Read(p)
    for i:=range(p[:n]) {
       p[i]=rot13(p[i])
    }
    return
}

The rot13Reader encapsulate any reader and call Read on said encapsulated Reader.
It returns the rot13'ed content, and the number of byte read.

这篇关于Reader接口和golang中的Read方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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