在Go中使用循环填充结构字段,以另一个函数的数据作为源
时间:2024-02-07
浏览:359
作者:佚名
偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《在Go中使用循环填充结构字段,以另一个函数的数据作为源》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!
我在 web 应用程序(fiber 框架)中有几个处理程序,其中一个处理程序从外部 api 检索数据,另一个处理程序获取该数据的子集并执行一些业务逻辑(即发送报告等)。
两个处理程序位于同一个包中。在 handler2.go 中,我能够取消引用 handler1.go 中的数据,并且我想使用该数据中的特定值来填充 handler2.go 中的结构字段。来自 handler1.go 的取消引用的数据本身就是一个可以循环的结构数组。
在 handler2.go 中,我有一个结构:
type Report struct {
contact string
date string
resource string
}
// get data from handler1.go function and use it to populate the Report struct
// each "report" is a struct, so need to create a list of structs
func getReportData() {
reportData := GetReport() // call function in handler1.go
for _, report := range *reportData {
fmt.Println(report.Date)
}
因此,我不想简单地打印数据(打印语句只是为了表明我可以访问所需的数据),而是想使用可以使用循环访问的数据中的特定项目来填充 report 结构,并且report.<key> 语法。
如何创建一个结构列表(使用报告结构),其中填充了我可以通过此 for 循环获取的数据?
对于 mvp ,我可以简单地格式化此结构列表(以 json 格式)并在 web 应用程序中显示端点。我只是在努力解决如何正确构建这些数据的问题。
正确答案
为了回答直接问题,如果我们假设 getreport() 返回的值具有 date、contact 和 resource 字段,那么您可以编写:
type Report struct {
contact string
date string
resource string
}
// Return a list (well, slice) of Reports
func getReportData() (reports []Report) {
reportData := GetReport()
for _, report := range reportData {
myReport := Report{
contact: report.Contact,
date: report.Date,
resource: report.Resource,
}
reports = append(reports, myReport)
}
return
}今天关于《在Go中使用循环填充结构字段,以另一个函数的数据作为源》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
