structtag go package seems not change tags inside function

72 Views Asked by At

im working to this code:

    package main

    import (
        "fmt"
        "reflect"

        "github.com/fatih/structtag"
    )

    type Person struct {
        Name    string `json:"name"`
        Age     int    `json:"age"`
        Address string `json:"address"`
    }

    func main() {
        p := &Person{
            Name:    "John",
            Age:     30,
            Address: "123 Main St",
        }
        p.setTag("Name","newtag")
        p.read1Tag ("Name")
    }

    func (p* Person) setTag(fieldName string,tagValue string){
        field, _ := reflect.TypeOf(*p).FieldByName(fieldName)
        tags, _ := structtag.Parse(string(field.Tag))
        tags.Delete("json")
        tag := &structtag.Tag{
            Key:  "json",
            Name: tagValue,
        }
        tags.Set(tag)
        field.Tag = reflect.StructTag(tags.String())
        tag1, _ := tags.Get("json")
        fmt.Println (tag1)
        field.Tag = reflect.StructTag(tags.String())
        }



    func (p Person) read1Tag (fieldName string) {
        field, _ := reflect.TypeOf(p).FieldByName(fieldName)
        tags, _ := structtag.Parse(string(field.Tag))
        tag, _ := tags.Get("json")
        fmt.Println (tag)
    }

I want to modify a json tag for the struct Person , field Name. The code , modify the tags inside the setTaG() function, but when i try to read it from main i have the old tag ( i have println the tag inside both the function ). I have defined the handler by reference, could someone help me , to mantain the tag out of the function? thanks.

i have try to run the code , and i would like to mantain the modified tag out of the setTag() ; so when i reread it , i would like to see the new value for the tag.

1

There are 1 best solutions below

3
NotX On

You can't modify the tags of p with that library and I wouldn't recommend trying it. structtag.Tag has no relation to the original struct - you pass a tag string to be parsed, which could come from anywhere as far asstructtag is concerned.

So, what you have to do instead: create a method like

func (p Person) getAdjustedTags() (adjustedTags structtag.Tags)

where you parse the tags from the Person, modify thoses parsed tags and return them (as adjustedTags). Use these adjustedTags for your further logic and pass them if need be.

You could even go a step further and just create a method like

func getAdjustedTags(withTags any) (adjustedTags structtag.Tags)

to support that for any struct with tags, since it has no relation to Person anyway.