Golang io/ioutil NopCloser

40

请问有人能够提供关于Golang的NopCloser函数的良好或任何解释吗?
我查看了一些资料,但除了Golang主要文档中的解释外,未能找到其他内容:

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

如果有任何指针或解释,请告知。谢谢。

3个回答

39

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

您可以在此 gorest fork 中看到一个示例,在 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("true"))), nil
        }

18

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


ioutil.NopCloser仅包装io.Reader。您可以创建自己的等效项以生成io.WriteCloser。 - krait
3
它还可以用在需要多次读取而不丢失内容的情况下,就像这个例子中一样:https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-its-content-2c6911805361 - Glenn 'devalias' Grant

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接