douhuan5073 2019-06-19 14:38
浏览 66
已采纳

如何在不使用字段名称作为字符串的情况下获取字段的标签?

Is it possible to fetch a field tag using a function that receives only the struct and the field itself ?

I know that I can do a thing like this:

reflect.TypeOf(x).FieldByName("FieldNameAsString").Tag

But I don't want to use the field's name as string in this case because it could be renamed in the future, so it is better to use the field itself instead.

type MyStruct struct {
    MyField string `thetag:"hello"`
}

func main() {
    x := MyStruct{}
    getTag(x, x.MyField)
}
  • 写回答

1条回答 默认 最新

  • dongtu1789 2019-06-19 16:12
    关注

    Use offsets to find the field:

    // getTag returns the tag for a field given a pointer to
    // a struct and a pointer to the field in that struct.
    func getTag(pv interface{}, pf interface{}) reflect.StructTag {
        v := reflect.ValueOf(pv)
        offset := reflect.ValueOf(pf).Pointer() - v.Pointer()
    
        t := v.Type().Elem()
        for i := 0; i < t.NumField(); i++ {
            f := t.Field(i)
            if f.Offset == offset {
                return f.Tag
            }
        }
        return ""
    }
    

    Run it on the playground.

    The code above assumes that the garbage collector does not move the struct between the to calls to Pointer. This assumption is true today, but may not true in the future. Use the unsafe package to make the code safe against future changes to the garbage collector:

    // getTag returns the tag for a field with the given offset
    // in the struct pointed to by pv.
    func getTag(pv interface{}, offset uintptr) reflect.StructTag {
        t := reflect.TypeOf(pv).Elem()
        for i := 0; i < t.NumField(); i++ {
            f := t.Field(i)
            if f.Offset == offset {
                return f.Tag
            }
        }
        return ""
    }
    

    Call it like this:

    x := MyStruct{}
    fmt.Println(getTag(&x, unsafe.Offsetof(x.MyField)))
    

    Run it on the Playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error