dimanche 1 janvier 2023

What is the difference for type assertion and reflect.Type.Implements

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
}

go playground





Aucun commentaire:

Enregistrer un commentaire