mercredi 3 juillet 2019

Generic attribution to field X, present across multiples types

Currently, I'm working with a set of structures, which define multiple versions of a document. Most of the fields are shared across these different versions, and the actual differences are pretty subtle. What I'm trying to do is refactor the code that parses this document. For that, it would be really good if I could generalize some attributions, where I don't need to know exactly what type I'm working to know that the type will have a specific field.

I've thought about using reflection but if I can avoid it I would.

Lets say we have:

type v1 struct{
  a int
}

and

type v2 struct{
 a int
 b string
}

what I would like to do is something like

func main(){
 var v1 v1
 var v2 v2

 foo(v1)
 foo(v2)
}


func foo (root interface{}){
  root.a = x
}

is it possible? or is there any other way?





Aucun commentaire:

Enregistrer un commentaire