when val := reflect.ValueOf(xx)
I found that
val.Interface().(io.Reader)
has the same effect as
val.Type().Implements(reflect.TypeOf(io.Reader).Elem())
,
what is the difference between the two? Performance? which way should I use?
when I tried the following code, I didn't find any difference.
package main
import (
"fmt"
"io"
"os"
"reflect"
)
func main() {
reader := reflect.TypeOf(new(io.Reader)).Elem()
closer := reflect.TypeOf(new(io.Closer)).Elem()
var f io.Reader = &os.File{}
val := reflect.ValueOf(f)
implementReader := val.Type().Implements(reader)
_, assertReader := val.Interface().(io.Reader)
fmt.Println(implementReader) // output: true
fmt.Println(assertReader) // output: true
implementCloser := val.Type().Implements(closer)
_, assertCloser := val.Interface().(io.Closer)
fmt.Println(implementCloser) // output: true
fmt.Println(assertCloser) // output: true
}
Aucun commentaire:
Enregistrer un commentaire