Golang io/ioutil NopCloser
Golang io/ioutil NopCloser
有没有人对 Golang 的 NopCloser
功能有好的解释?
我环顾四周,但除了 Golang 的主要文档的解释之外没有找到任何东西:
NopCloser returns a ReadCloser with a no-op Close method wrapping the
provided Reader r.
如有任何指点或解释,我们将不胜感激。谢谢
它用于需要 io.ReadCloser
但您当前的对象(例如 bytes.Buffer
)不提供关闭函数的函数。
每当您需要 return 和 io.ReadCloser
时,在确保 Close()
可用的同时,您可以使用 NopCloser
来构建这样的 ReaderCloser。
你可以在这个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("true"))), nil
}
当您需要提供具有 Close
功能的项目时,但当
Close
对该项目没有任何意义。这样,功能就差不多了
什么都不做:
func (nopCloser) Close() error { return nil }
https://github.com/golang/go/blob/go1.16.3/src/io/io.go#L620
有没有人对 Golang 的 NopCloser
功能有好的解释?
我环顾四周,但除了 Golang 的主要文档的解释之外没有找到任何东西:
NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.
如有任何指点或解释,我们将不胜感激。谢谢
它用于需要 io.ReadCloser
但您当前的对象(例如 bytes.Buffer
)不提供关闭函数的函数。
每当您需要 return 和 io.ReadCloser
时,在确保 Close()
可用的同时,您可以使用 NopCloser
来构建这样的 ReaderCloser。
你可以在这个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("true"))), nil
}
当您需要提供具有 Close
功能的项目时,但当
Close
对该项目没有任何意义。这样,功能就差不多了
什么都不做:
func (nopCloser) Close() error { return nil }
https://github.com/golang/go/blob/go1.16.3/src/io/io.go#L620