How to get the name of an struct/interface?
package crud
type User struct {
ID uint
Name string
Email string
}
package main
import "./crud"
func get_struct(value interface{}){
// print "User"
}
func main(){
get_struct(&crud.User{})
}
The reflect
package provides this; you simply create a new reflect.Value
from the variable and inspect its type:
func get_struct(value interface{}){
var name string
ref := reflect.ValueOf(value)
if ref.IsValid() {
name = ref.Type().Name()
} else {
name = "nil"
}
fmt.Println(name)
}
Note: you may not get the output you want if a pointer is passed. You may want to consider using Type.String()
over Type.Name()
.