登录
首页 >  Golang >  Go问答

Convert ...interface{} to a Struct in Go

来源:stackoverflow

时间:2024-03-03 18:27:27 415浏览 收藏

Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《Convert ...interface{} to a Struct in Go》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!


问题内容

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

在其中一个函数中,参数的数量更多,并且在函数定义中,我像这样单独转换数组项

someVar := data[0].(string)

现在,当我通常处理 1-2 个参数时,这种方法就很好了。但当参数数量增加时,它就会变得乏味。

那么有没有一种更清晰的方法可以按照元素出现的顺序将元素解析为结构体?

我的目标是以一种更简洁的方式做到这一点,而不是单独从数组中获取一个并转换为字符串变量。

解释场景的示例代码 https://go.dev/play/p/oscajyylw0w


正确答案


使用 reflect 包设置 interface{} 切片中值的字段。这些字段必须为 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")

Playground Example

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Convert ...interface{} to a Struct in Go》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>