Go – 将…interface{}转换为结构体

huangapple go评论84阅读模式
英文:

Go - converting ...interface{} to a struct

问题

我有一个场景,我正在调用一个函数,利用一个常见的后台工作线程,该函数的参数为func somefunction(data ...interface{}),以便在整个应用程序中实现通用性和可重用性。

在其中一个函数中,参数的数量较多,在函数定义中,我将数组项逐个转换为:

someVar := data[0].(string)

当我通常处理1-2个参数时,这种方法是可以接受的。但是当参数的数量增加时,这种方法变得繁琐。

所以,有没有一种更简洁的方法按照它们出现的顺序将元素解析为结构体?

我的目标是以一种更简洁的方式完成这个操作,而不是逐个从数组中获取一个并将其转换为字符串变量。

示例代码解释了这个场景:https://go.dev/play/p/OScAjyyLW0W

英文:

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

答案1

得分: 3

使用reflect包从interface{}的切片中设置值的字段。这些字段必须是导出的

// setFields将dest指向的结构体中的字段设置为args。这些字段必须是导出的。
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  // <-- 注意导出的字段名。
	Name     string
	Location string
}

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

Playground示例

英文:

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  // &lt;-- note exported field names.
	Name     string
	Location string
}

var pi PersonInfo
setFields(&amp;pi, &quot;A001&quot;, &quot;John Doe&quot;, &quot;Tomorrowland&quot;)

Playground Example.

huangapple
  • 本文由 发表于 2022年2月23日 01:32:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/71225798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定