Some ideas for detect changes in a struct value?

hi everybody. I’m new in golang and i try to detect when a api client make a change in some struct value but I failed to do well. i need know if some struct attribute value has changed in runtime. can someone help me please. (e.g.)

type Foo struct{
	PublicA string
	PublicB int
	privateAttr string
}

func (x *Foo) PrivateAttr() string{
	return "somoString"+x.privateAttr;
}

func main(){
        foo := getFooFromSource() //get a something like {"publicAValue","publicBValue","privateAttrValue"}
        foo.PublicA = "other string" //the PublicA attribute is dirty
        encoded, _ := json.Marshal(&foo)
        exportFooToSomeNewLocation(string(encoded)) 
}

question one: how is the best way to know when PublicA value change or is not the loaded value from source ( foo.PublicA = “otther string” ) (the value is dirty)

question two: how achievement, that when I export the structure to a json get the value given by the function Foo.PrivateAttr() but still use json.Marchal

Two options that strike me are to

  • not expose the field to begin with other than via an accessor like the privateAttr and possibly a corresponding setter, or
  • keep a hash of the struct contents and verify this when you need to know if it’s changed.

You can implement json.Marshaler to control the JSON representation of the struct yourself.

2 Likes

If you are just trying to check one struct value, then you can try spawning another go routine to check to see if the value changed using a combination of for and select statement with channels.

If the string value changed at runtime you would send the newly changed string down the channel and it would trigger a case statement in the for + select statement in the go routine so then you would know a value has changed.

thx @calmh are good ideas, i looked for examples and found this on how to implement the interface Marshaler kendellfab/golang-json-marshall gist

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.