有没有人对Golang的NopCloser功能有任何好处或解释?
我环顾四周,但除了Golang的主要文档解释之外没有找到任何东西:
NopCloser返回一个ReadCloser,其中包含一个无操作的Close方法,用于包装提供的Reader r.
任何指针或解释将不胜感激.谢谢.
Von*_*onC 23
每当你需要返回一个io.ReadCloser,同时确保一个Close()可用时,你可以用a NopCloser来构建这样一个ReaderCloser.
//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
}
Run Code Online (Sandbox Code Playgroud)
One*_*One 10
它用于需要的函数,io.ReadCloser但您当前的对象(例如a bytes.Buffer)不提供Close函数.