Golang io/ioutil NopCloser是一个函数,它返回一个实现了io.ReadCloser接口的对象。

huangapple go评论77阅读模式
英文:

Golang io/ioutil NopCloser

问题

有人能给出关于Golang的NopCloser函数的好的或任何解释吗?我找了一下,但除了Golang的主要文档中的解释之外,没有找到其他任何东西:

> NopCloser返回一个包装提供的Reader r的无操作Close方法的ReadCloser。

如果有任何指导或解释,将不胜感激。谢谢。

英文:

Does anyone have a good or any explanation of Golang's NopCloser function? <br> I looked around but failed to find anything besides Golang's main doc's explanation of:

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

Any pointers or explanation would be appreciated. Thanks.

答案1

得分: 39

每当你需要返回一个 io.ReadCloser,同时确保有一个 Close() 方法可用时,你可以使用 NopCloser 来构建这样的 ReaderCloser。

你可以在这个 gorest 的分支 中的 util.go 文件中看到一个示例。

// 将接口 i 中的数据编组为一个字节切片,使用 mime 中指定的编组器/解组器。
// 在使用 gorest.RegisterMarshaller 注册编组器/解组器之前,必须先注册。
func InterfaceToBytes(i interface{}, mime string) (io.ReadCloser, error) {
    v := reflect.ValueOf(i)
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    switch v.Kind() {
    case reflect.Bool:
        x := v.Bool()
        if x {
            return ioutil.NopCloser(bytes.NewBuffer([]byte("true"))), nil
        }
        // ...
    }
}
英文:

Whenever you need to return an io.ReadCloser, while making sure a Close() is available, you can use a NopCloser to build such a ReaderCloser.

You can see one example in this fork of gorest, in util.go

//Marshals the data in interface i into a byte slice, using the Marhaller/Unmarshaller specified in mime.
//The Marhaller/Unmarshaller must have been registered before using gorest.RegisterMarshaller
func InterfaceToBytes(i interface{}, mime string) (io.ReadCloser, error) {
    v := reflect.ValueOf(i)
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    switch v.Kind() {
    case reflect.Bool:
        x := v.Bool()
        if x {
            return ioutil.NopCloser(bytes.NewBuffer([]byte(&quot;true&quot;))), nil
        }

答案2

得分: 17

这是用于需要io.ReadCloser的函数,但是你当前的对象(例如bytes.Buffer)没有提供Close函数。

英文:

It's used for functions that require io.ReadCloser but your current object (for example a bytes.Buffer) doesn't provide a Close function.

答案3

得分: 2

这是用于在需要提供具有Close函数的项目时使用的,但是对于该项目来说,Close函数并没有实际意义。因此,该函数基本上什么也不做:

func (nopCloser) Close() error { return nil }

https://github.com/golang/go/blob/go1.16.3/src/io/io.go#L620

英文:

It is for when you need to supply an item that has a Close function, but when
Close doesn't really make sense for that item. As such, the function pretty much
does nothing:

func (nopCloser) Close() error { return nil }

https://github.com/golang/go/blob/go1.16.3/src/io/io.go#L620

huangapple
  • 本文由 发表于 2015年1月27日 05:22:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/28158990.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定