-2

So I'm trying to make a generic function that returns to me a slice of elements with the fields of any structure. For example I have the following.

type Car struct{
   Doors  int
   wheels int
   color  string
}

type Person struct{
   name string
   age  int
}

and each one has a function where I get the fields of those structures like this:

func (car *Car) GetFields() []interface{} {
    var structure = reflect.ValueOf(car).Elem()
    numCols := structure.NumField()
    var columns []interface{}

    for i := 0; i < numCols; i++ {
        field := structure.Field(i)
        columns = append(columns, field.Addr().Interface())
    }

    return columns
}

func (person *Person) GetFields() []interface{} {
    var structure = reflect.ValueOf(person).Elem()
    numCols := structure.NumField()
    var columns []interface{}

    for i := 0; i < numCols; i++ {
        field := structure.Field(i)
        columns = append(columns, field.Addr().Interface())
    }

    return columns
}

As you can see the code just gets repetitive and it's basically the same

I've tried different things to with no success such as sending structures in a parameter.

How can I create a single generic function that does the same for every structure?

0 Answers0