Home > Net >  Go - converting ...interface{} to a struct
Go - converting ...interface{} to a struct

Time:02-23

I have a scenario where I'm calling a function leveraging a common background worker thread that has arguments as func somefunction(data ...interface{}) to be generic and reusable across the application.

In one of the functions, the number of arguments are more and in the unction definition, I am casting the array items individually like

someVar := data[0].(string)

Now this approach is fine when I'm usually dealing with 1-2 arguments. But it becomes tedious when the number of arguments increases.

So is there a cleaner way to parse the elements into a struct in the order of their appearance?

My objective is to do this in a cleaner way rather than individually getting one from array and casting to a string variable.

Sample code explaining the scenario https://go.dev/play/p/OScAjyyLW0W

CodePudding user response:

Use the reflect package to set fields on a value from a slice of interface{}. The fields must be exported.

// setFields set the fields in the struct pointed to by dest
// to args. The fields must be exported.
func setFields(dest interface{}, args ...interface{}) {
    v := reflect.ValueOf(dest).Elem()
    for i, arg := range args {
        v.Field(i).Set(reflect.ValueOf(arg))
    }
}

Call it like this:

type PersonInfo struct {  
    ID       string  // <-- note exported field names.
    Name     string
    Location string
}

var pi PersonInfo
setFields(&pi, "A001", "John Doe", "Tomorrowland")

Playground Example.

  •  Tags:  
  • go
  • Related