dimanche 8 décembre 2019

Metaprogramming - Set fields of arbitary structs in run time

I want to implement a function that given an arbitrary struct will return of deepcopy of the struct with the string fields set to the value field_name+"X". Assume all structs will contain only string fields.

To better explain:

type A struct {
  var_1 string
  var_2 string
}

type B struct {
  var_3 string
  var_4 string
  var_5 string
}   

a := A{}
b := B{}

aCopy := some_func(a)
bCopy := some_func(b)

fmt.Println(aCopy)
fmt.Println(bCopy)
fmt.Println(a)
fmt.Println(b)

Then the program should print

{var_1X, var_2X}
{var_3X, var_4X, var_5X}
{}
{}

I know I can get the field name using reflection but I do not know how to do the rest.

I am expecting the function to have the following signature:

func some_func(s interface{}) interface{}




Aucun commentaire:

Enregistrer un commentaire