从传递给函数的结构体中获取名称。

huangapple go评论122阅读模式
英文:

get name from struct passed to function

问题

如何获取结构体/接口的名称?

#pkg
包crud

  1. 类型User struct {
  2. ID uint
  3. Name string
  4. Email string
  5. }

#main

  1. main
  2. 导入"./crud"
  3. func get_struct(value interface{}) {
  4. // 打印"User"
  5. }
  6. func main() {
  7. get_struct(&crud.User{})
  8. }
英文:

How to get the name of an struct/interface?

#pkg
package crud

  1. type User struct {
  2. ID uint
  3. Name string
  4. Email string
  5. }

#main

  1. package main
  2. import "./crud"
  3. func get_struct(value interface{}){
  4. // print "User"
  5. }
  6. func main(){
  7. get_struct(&crud.User{})
  8. }

答案1

得分: 1

reflect 包提供了这个功能;你只需从变量创建一个新的 reflect.Value 并检查其类型:

  1. func get_struct(value interface{}) {
  2. var name string
  3. ref := reflect.ValueOf(value)
  4. if ref.IsValid() {
  5. name = ref.Type().Name()
  6. } else {
  7. name = "nil"
  8. }
  9. fmt.Println(name)
  10. }

注意:如果传递了一个指针,可能无法得到你想要的输出。你可能需要考虑使用 Type.String() 而不是 Type.Name()

Playground

英文:

The reflect package provides this; you simply create a new reflect.Value from the variable and inspect its type:

  1. func get_struct(value interface{}){
  2. var name string
  3. ref := reflect.ValueOf(value)
  4. if ref.IsValid() {
  5. name = ref.Type().Name()
  6. } else {
  7. name = "nil"
  8. }
  9. fmt.Println(name)
  10. }

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().

Playground

huangapple
  • 本文由 发表于 2015年4月16日 03:01:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/29658629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定