Go - 将 ...interface{} 转换为结构
Go - converting ...interface{} to a struct
我有一个场景,我正在调用一个利用公共后台工作线程的函数,该线程的参数为 func somefunction(data ...interface{})
,以便在整个应用程序中通用且可重用。
在其中一个函数中,参数的数量更多,在函数定义中,我将数组项单独转换为
someVar := data[0].(string)
现在,当我通常处理 1-2 个参数时,这种方法很好。但是当参数的数量增加时,它变得乏味。
那么有没有更简洁的方法来将元素按照出现的顺序解析为结构?
我的 objective 是以更简洁的方式执行此操作,而不是单独从数组中获取一个并转换为字符串变量。
解释场景的示例代码https://go.dev/play/p/OScAjyyLW0W
使用 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))
}
}
这样称呼它:
type PersonInfo struct {
ID string // <-- note exported field names.
Name string
Location string
}
var pi PersonInfo
setFields(&pi, "A001", "John Doe", "Tomorrowland")
我有一个场景,我正在调用一个利用公共后台工作线程的函数,该线程的参数为 func somefunction(data ...interface{})
,以便在整个应用程序中通用且可重用。
在其中一个函数中,参数的数量更多,在函数定义中,我将数组项单独转换为
someVar := data[0].(string)
现在,当我通常处理 1-2 个参数时,这种方法很好。但是当参数的数量增加时,它变得乏味。
那么有没有更简洁的方法来将元素按照出现的顺序解析为结构?
我的 objective 是以更简洁的方式执行此操作,而不是单独从数组中获取一个并转换为字符串变量。
解释场景的示例代码https://go.dev/play/p/OScAjyyLW0W
使用 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))
}
}
这样称呼它:
type PersonInfo struct {
ID string // <-- note exported field names.
Name string
Location string
}
var pi PersonInfo
setFields(&pi, "A001", "John Doe", "Tomorrowland")