dongqiu3709 2017-07-07 15:31
浏览 16

通过Golang的界面进行反思

I have some structs in Go, they implement a common method, so I created an interface for it (Because in some methods I need to receive an element of the type of the interface).Basically I have something like:

type Model interface {
    CommonMethod() string
}

Then I have something like 10 struct that implements that CommonMethod, for example:

type Contact struct {
    ...Some fields
}

func (Contact) CommonMethod() string {
    return "Something"
}

Until here everything is ok. Then I have a generic method that will receive 2 instances of Model, the proptotype for this function is:

func MyFunction(NewObject Model,PreviousObject Model)

In that function I need to compare the fields: name of the fields and values between the 2 objects. I am trying to make it using Reflect but if I use reflect.ValueOf() I only get the value of the attributes and I don't see any way to get the name. So, is there a way that I can get the struct that comes inside the Model interface so then I can use reflect.TypeOf()?

EDIT:

If I set this:

NewObjectListing := reflect.TypeOf(NewObject)
numFields := NewObjectListing.NumField()

I get this error: panic: reflect: NumField of non-struct type

But if I use:

NewObjectListing := reflect.ValueOf(NewObject)
numFields := NewObjectListing.NumField()

There is no error but then I cannot do things like NewObjectListing.Field(i).Name

  • 写回答

1条回答 默认 最新

  • dsgdfh302506 2017-07-11 01:52
    关注
    1. reflect.TypeOf() just returns a type of the input value WITHOUT ANY VALUE
    2. you won't able to get any field from JUST a type
    3. reflect.ValueOf() returns the value of the input value
    4. if the type you got from the input is a struct, you'll be able to get a numField from the INPUT VALUE which returns by reflect.ValueOf.

    1. reflect.ValueOf(*).Field(n) returns the VALUE of the (n+1)th field of your struct
    2. if your got nothing from the method above, assign a value to the field above.
    3. the best way is to assign values to every field of your input struct

    4. reflect.TypeOf(*).Field(n).Name() returns the NAME of the (n+1)th field.

    5. if you want to correctly use this method, change your field name from a lower one to title one(hello -> Hello)
    6. if reflect.ValueOf(*).Field(n).CanInterface() is true, your can get your field n+1's name by reflect.ValueOf(*).Field(n).Name()
    评论

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元