doujiang1001
2018-08-29 11:49
浏览 1.2k
已采纳

如何将io.Reader转换为io.ReadCloser? [重复]

This question already has an answer here:

I have an io.Reader that doesn't require closing:

stringReader := strings.NewReader("shiny!")

And I want to pass it to a method that receives an io.ReadCloser

func readAndClose(source io.ReadCloser) {
    ...
}

How do I turn the io.Reader into a io.ReadCloser without specially creating a struct that implements the Close method?

</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案:

  • Golang io / ioutil NopCloser 2个答案

    我有一个 io.Reader 不需要关闭: \ n

      stringReader:= strings.NewReader(“ shiny!”)
       
     
     

    我想将其传递给接收 io.ReadCloser

      func readAndClose(源io.ReadCloser){
     ... 
    } 
       \  n 
     

    如何将 io.Reader 转换为 io.ReadCloser ,而无需专门创建实现 Close 方法的结构 ?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douhuo1738 2018-08-29 11:49
    已采纳

    If you're certain that your io.Reader doesn't require any actual closing, you can wrap it with an ioutil.NopCloser.

    From the godoc:

    NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.

    So we can apply it like:

    stringReader := strings.NewReader("shiny!")
    stringReadCloser := ioutil.NopCloser(stringReader)
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题