2015-01-26 71 views
6

有沒有人對Golang的NopCloser函數有很好的或任何的解釋?
我環顧四周,但沒有找到除了的Golang的主要文檔的解釋任何東西:Golang io/ioutil NopCloser

NopCloser返回ReadCloser與無操作關閉方法包裹 提供讀寫器R。

任何指針或解釋將不勝感激。謝謝。

回答

10

無論何時您需要退還io.ReadCloser,同時確保Close()可用,您可以使用NopCloser構建此類ReaderCloser。

你可以看到在這個fork of gorest一個例子,在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 
     } 
2

它用於需要io.ReadCloser的函數,但當前對象(例如bytes.Buffer)不提供Close功能。

+0

ioutil.NopCloser只包裝io.Reader。你可以創建自己的等價物來產生一個io.WriteCloser – krait 2015-01-26 22:25:59

+0

@Krait,這很好。 – OneOfOne 2015-01-27 16:24:05