package runtimeimport ()func getTag( reflect.StructField) string {return .Tag.Get("json")}func ( reflect.StructField) bool {if .PkgPath != "" {if .Anonymous { := .Typeif .Kind() == reflect.Ptr { = .Elem() }if .Kind() != reflect.Struct {returntrue } } else {// private fieldreturntrue } } := getTag()return == "-"}typeStructTagstruct { Key string IsTaggedKey bool IsOmitEmpty bool// IsOmitZero is whether the field has the omitzero option, which encoding/json has from Go 1.24: it is // false with an older Go, whose encoding/json ignores the option. IsOmitZero bool IsString bool Field reflect.StructField// QuotedKey is Key as a JSON string, if Key may need an escape: a name of the v2 semantics may have any // character. QuotedKey string}typeStructTags []*StructTagfunc ( StructTags) ( string) bool {for , := range {if .Key == {returntrue } }returnfalse}func isValidTag( string) bool {if == "" {returnfalse }for , := range {switch {casestrings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", ):// Backslash and quote chars are reserved, but // otherwise any punctuation chars are allowed // in a tag name.case !unicode.IsLetter() && !unicode.IsDigit():returnfalse } }returntrue}func ( reflect.StructField) *StructTag { := .Name := getTag() := &StructTag{Field: } := strings.Split(, ",")iflen() > 0 {if [0] != "" && isValidTag([0]) { = [0] .IsTaggedKey = true } } .Key = iflen() > 1 {for , := range [1:] {switch {case"omitempty": .IsOmitEmpty = truecase"omitzero": .IsOmitZero = omitZeroOptioncase"string": .IsString = true } } }return}// NamedField is a field of a struct, or of a struct embedded in it whose fields are promoted, which has a key in the// JSON object.typeNamedFieldinterface {// Depth is how deep the field is in the structs embedded in the struct: 0 for a field of the struct itself.Depth() int// IsTaggedKey reports whether the key is the name in the field's tag.IsTaggedKey() bool}// DominantField returns which one of fields, the fields of a struct which have the same key, is written and read// with the key, as encoding/json chooses it: the least deep one, or, if more than one are at that depth, the only// one of them with the key in its tag. It returns -1 when none is.func [ NamedField]( []) int { := [0].Depth()for , := range [1:] { = min(, .Depth()) } := -1var , intfor , := range {if .Depth() != {continue } ++if .IsTaggedKey() { ++ = } elseif == 1 { = } }if > 1 && != 1 {return -1 }return}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.