dongxu3029 2015-06-18 10:10
浏览 12
已采纳

为什么使用裸收益和正常收益会给我不同的结果?

I'm playing around with Golang tour and I wonder why using naked return give me the correct result but the normal one doesn't. This is the exercise that I have this problem https://tour.golang.org/methods/12.

The objective is to create a reader that can decipher rot13. and the rot13 function is already tested.

func (r rot13Reader) Read(b []byte) (n int, err error) {
    n, err =  r.r.Read(b)
    for i, v := range b {
        b[i] = rot13(v)
    }
    return
}

The code above give me the correct result.

func (r rot13Reader) Read(b []byte) (int, error) {
    for i, v := range b {
    b[i] = rot13(v)
    }
    return r.r.Read(b)
}

And this doesn't change anything from the input stream.

Could anybody explain why? Thank you in advance.

  • 写回答

2条回答 默认 最新

  • drfu80954 2015-06-18 10:27
    关注

    It's not a problem with returns, but in the first case you're reading the data in before transforming it and in the second case you're transforming junk in a buffer and only then reading in the data (and simply passing what has been read from the underlying reader).

    While this is not required for correctness, I'd suggest you don't transform the whole buffer every time, but only the portion that has been read, i.e. changing your first example from for i, v := range b to for i, v := range b[:n]. That's because io.Read call is not able to modify length of slice b, but just its content.

    Take a look at the documentation of io.Reader, it should give you some more idea on how this interface is expected to work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 悬赏Python-playwright部署在centos7上
  • ¥15 psoc creator软件有没有人能远程安装啊
  • ¥15 快速扫描算法求解Eikonal方程咨询
  • ¥20 我的是道格手机,重置后屏幕右上角出现红色字的未写入tee key 和未写入google key请问怎么去掉啊
  • ¥30 关于R语言运行分区生存模型中的问题!
  • ¥15 校内二手商品转让网站
  • ¥20 高德地图聚合图层MarkerCluster聚合多个点,但是ClusterData只有其中部分数据,原因应该是有经纬度重合的地方点,现在我想让ClusterData显示所有点的信息,如何实现?
  • ¥100 求Web版SPC控制图程序包调式
  • ¥20 指导如何跑通以下两个Github代码
  • ¥15 大家知道这个后备文件怎么删吗,为啥这些文件我只看到一份,没有后备呀