Skip to content

Instantly share code, notes, and snippets.

@xieyuschen
Created January 23, 2021 09:49
Show Gist options
  • Save xieyuschen/e5b9c10c16b5b20aae256317fac9ca55 to your computer and use it in GitHub Desktop.
Save xieyuschen/e5b9c10c16b5b20aae256317fac9ca55 to your computer and use it in GitHub Desktop.
Incrementally Update Struct Golang

Incrementally Update Struct Golang

增量删除是很重要的,比如说在update的方法里面会出现这样的情况。

type demoStruct struct {
	Replaced string
	Remain   string
}
func main() {
	oldInfo := demoStruct{Replaced: "You can see me no more", Remain: "I still here"}
	fmt.Println(oldInfo.Replaced,"  ",oldInfo.Remain)
	newInfo := demoStruct{Replaced: "I replace my ancester:)"}
	incrementallyUpdate(&oldInfo,&newInfo)
	fmt.Println(oldInfo.Replaced,"  ",oldInfo.Remain)
}
func incrementallyUpdate(update *demoStruct,info *demoStruct){
	updateS:=reflect.ValueOf(update).Elem()
	infoS:=reflect.ValueOf(info).Elem()
	for i:=0;i<updateS.NumField();i++{
		f:=updateS.Field(i)
		f_info:=infoS.Field(i)
		if !f_info.IsZero(){
			f.Set(reflect.Value(f_info))
		}
	}
	return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment