繁体   English   中英

如何从 golang 中的字段类型内部访问结构标记

[英]How to access a struct tag from inside a field-type in golang

我想知道是否以及如何从该结构中使用的自定义类型访问结构标记集。

type Out struct {
    C Custom `format:"asd"`
}

type Custom struct {
}

func (c Custom) GetTag() string {
    // somehow get access to `format:"asd"`
}

我的目标是能够为解组/编组定义时间格式,并处理由 structtag 参数化的实际时间解组。

谢谢

那不可能 标签属于结构域,而不是类型。 因此,类型C无法知道使用了哪个标签。 另外,如果发生以下情况,它将如何工作:

type A struct {
  C Custom `tag1`
}
type B struct {
  C Custom `tag2`
}

你可以通过反思来做到这一点。

type Out struct {
    C Custom `format:"asd"`
}

type Custom struct {
}

func (c Custom) GetTag() string {
    t := reflect.TypeOf(Out{})

    f, ok := t.FieldByName("C")
    if !ok {
        return ""
    }

    return f.Tag.Get("format")
}

既然问题已经reflection标记,去你需要在通过这条道路Out型以某种方式您UN /编组方法,如

var o *Out // nil-pointer so we don't waste any space

c := Custom{}

// bs is of type []byte{}

err := MyUnmarshalerWithReflect(bs, &c, o)

因此,也许这是一个XY问题 ,直接使用所需的时间格式Unmarshal就更直观了,例如

err := MyUnmarshalerWithTimeFormat(bs, &c, "2006-01-02")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM