vendredi 26 octobre 2018

Print a type without using reflrect and create new object

In below code, in order to show the expected type, I have to create a new object and call reflect.TypeOf on it.

package main

import (
    "fmt"
    "reflect"
)

type X struct {
    name string
}

func check(something interface{}) {
    if _, ok := something.(*X); !ok {
        fmt.Printf("Expecting type %v, got %v\n", 
            reflect.TypeOf(X{}), reflect.TypeOf(something))
    }
}

func main() 
    check(struct{}{})
}

Perhaps that object creation is not an overhead, but I still curious to know a better way. Are there something like X.getName() or X.getSimpleName() in java?





Aucun commentaire:

Enregistrer un commentaire